如何计算没有环的矩阵的欧几里得长度? [英] How to calculate Euclidean length of a matrix without loops?
问题描述
似乎答案很简单,但我很沮丧.我有一个Nx3矩阵的矩阵,其中第1个第2列和第3列是第n个项目的X Y和Z坐标.我想计算从原点到项目的距离.以非矢量形式,这很容易.
It seems like the answer to this should be simple, but I am stumped. I have a matrix of Nx3 matrix where there 1st 2nd and 3rd columns are the X Y and Z coordinates of the nth item. I want to calculate the distance from the origin to the item. In a non vectorized form this is easy.
distance = norm([x y z]);
distance = norm([x y z]);
或
距离= sqrt(x ^ 2 + y ^ 2 + z ^ 2);
distance = sqrt(x^2+y^2+z^2);
但是,以矢量化形式,它并不是那么简单.当您将矩阵传递给范数时,它不再返回欧几里得长度.
However, in vectorized form its not so simple. When you pass a matrix to norm it no longer returns the Euclidean length.
distance = norm(matrix); %不起作用
distance = norm(matrix); %doesn't work
和
距离= sqrt(x(:,1).* x(:,1)+ y(:,2).* y(:,2)+ z(:,3).* z(:,3 ));只是看起来很乱
distance = sqrt(x(:,1).*x(:,1)+y(:,2).*y(:,2)+z(:,3).*z(:,3)); %just seems messy
有更好的方法吗?
推荐答案
尝试一下:
>> xyz = [1 2 3; 4 5 6; 7 8 9; 2 8 4]
xyz =
1 2 3
4 5 6
7 8 9
2 8 4
>> distance = sqrt(sum(xyz.^2, 2))
distance =
3.74165738677394
8.77496438739212
13.9283882771841
9.16515138991168
这篇关于如何计算没有环的矩阵的欧几里得长度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!