How to calculate Euclidean length of a matrix without loops?
Asked Answered
C

5

6

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?

Cityscape answered 17/3, 2011 at 16:56 Comment(0)
P
14

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
Parasiticide answered 17/3, 2011 at 17:1 Comment(0)
M
3

Yes, there is.

distance = sqrt(sum(matrix.^2,2)); %# matrix is [x y z]
Mcmullen answered 17/3, 2011 at 16:59 Comment(0)
A
1

To obtain the norms of vectors of a matrix

vecnorm( A, p, dim)

has been introduced in MATLAB 2017b. For the given question the Euclidian Distance (L2 norm), set p = 2 , and row-wise operations, set dim = 2.

vecnorm( X, 2, 2)
Anelace answered 4/9, 2019 at 13:56 Comment(0)
P
0

I think the way to go is distance = sqrt(matrix(:,1).^2+matrix(:,2).^2+matrix(:,3).^2).

Loops in Matlab are just too slow. Vector operations are always preferred (as I'm sure you know). Additionally, using .^2 (element-wise squaring) does not have to look each column of your matrix twice, so this would be even faster.

Proptosis answered 17/3, 2011 at 17:3 Comment(0)
P
-1

Using h2O

h2o.init()
df1<-as.h2o(matrix1)
df2<-as.h2o(matrix2)
distance<-h2o.distance(df1,df2,"l2")
#l2 for euclidean distance
Picnic answered 20/8, 2017 at 14:15 Comment(1)
This is not even valid MATLAB syntax.Tent

© 2022 - 2024 — McMap. All rights reserved.