Calculating the norm of each row in a matrix

Jack_111 picture Jack_111 · Aug 20, 2013 · Viewed 17.8k times · Source

I have a Nx3 matrix (A) the columns are X,Y,Z respectively. I want to calculate the norm that is sqrt(X^2+Y^2+Z^2) for each row. I did a for loop for that:

for i = 1:length(A)
Result(i) = norm(A(i,:))
end

is there any other way to do it avoiding for loop?

Thanks

Answer

Dan picture Dan · Aug 20, 2013

You can do it like this:

sqrt(sum(A.^2, 2))

Your method returns a 1x3 where this returns a 3x1. So if you want you can transpose it but I doubt you really need to.