How to calculate the Euclidean matrix length without loops?

The answer seems to be simple, but I'm at a dead end. I have an Nx3 matrix matrix, where the 1st and 3rd columns are the XY and Z coordinates for the nth element. I want to calculate the distance from the beginning to the element. In a non-vectorized way, this is easy.

distance = norm ([xyz]);

or

distance = sqrt (x ^ 2 + y ^ 2 + z ^ 2);

However, in a vectorized form it is not so simple. When you pass a matrix back to normal, it no longer returns the Euclidean length.

distance = norm (matrix); % does not work.

and

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

Is there a better way to do this?

+6
5

:

>> 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
+14

, .

distance = sqrt(sum(matrix.^2,2)); %# matrix is [x y z]
+3

vecnorm( A, p, dim)

MATLAB 2017b. ( L2), p = 2, dim = 2.

vecnorm( X, 2, 2)
+1

, distance = sqrt(matrix(:,1).^2+matrix(:,2).^2+matrix(:,3).^2).

The loops in Matlab are too slow. Vector operations are always preferable (as I am sure you know). In addition, use .^2(elementary squaring) should not look every column of your matrix twice, so it will be even faster.

0
source

Using h2O

h2o.init()
df1<-as.h2o(matrix1)
df2<-as.h2o(matrix2)
distance<-h2o.distance(df1,df2,"l2")
#l2 for euclidean distance
-1
source

All Articles