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?
Try this:
Using h2O
Yes, there is.
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.