Come calcolare la lunghezza euclidea di una matrice senza loop?
-
27-10-2019 - |
Domanda
Sembra che la risposta a questo deve essere semplice, ma io sono perplesso. Ho una matrice di matrice NX3 dove 1 ° 2 ° e 3 colonne sono X Y e Z della voce n-esimo. Voglio calcolare la distanza dall'origine alla voce. In un non Vettorializzare forma questo è facile.
= distanza norma ([x y z]);
o
distanza = sqrt (x ^ 2 + y ^ 2 + z ^ 2);
Tuttavia, in forma vettorializzare non è così semplice. Quando si passa una matrice alla norma non è più restituisce la lunghezza euclidea.
= distanza norma (matrice); % Non funziona
e
distanza = sqrt (x (:, 1) * x (:., 1) + y (:, 2) * y (:., 2) + z (:., 3) * z (:, 3 )); % Sembra proprio disordinato
C'è un modo migliore per fare questo?
Soluzione
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
Altri suggerimenti
Yes, there is.
distance = sqrt(sum(matrix.^2,2)); %# matrix is [x y z]
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)
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.
Using h2O
h2o.init()
df1<-as.h2o(matrix1)
df2<-as.h2o(matrix2)
distance<-h2o.distance(df1,df2,"l2")
#l2 for euclidean distance