Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to calculate Euclidean length of a matrix without loops?

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]);

or

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); %doesn't work

and

distance = sqrt(x(:,1).*x(:,1)+y(:,2).*y(:,2)+z(:,3).*z(:,3)); %just seems messy

Is there a better way to do this?

like image 673
Miebster Avatar asked Mar 17 '11 16:03

Miebster


2 Answers

Try this:

>> 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
like image 135
b3. Avatar answered Sep 30 '22 13:09

b3.


Yes, there is.

distance = sqrt(sum(matrix.^2,2)); %# matrix is [x y z]
like image 41
Jonas Avatar answered Sep 30 '22 12:09

Jonas