vecnorm - applying norm function to rows of matrix-Matlab

vecnorm matlab 2017 (5)

From version 2017b onwards, you can use vecnorm.

This question already has an answer here:

I have a 3 columns, n rows matrix:

[ a,b,c;
  g,h,i; ]

I want to apply the norm function to each of the rows, and get a 1xn matrix containing the norms:

[ norm([a,b,c]);
  norm([g,h,i]); ]

I could do this with a for-loop, but is there a better way?

If readability is a bigger consideration than performance you might also consider:

norms = cellfun(@norm,num2cell(A,2));

This pattern is also adaptable to other operations along one dimension you might want to perform where MATLAB doesn't support it natively.

What about

 norms = sqrt(sum(A.^2,1))


 norms = sqrt(sum(A.^2,2))?

depending on whether your coordinates are in rows or in columns.

if the first dimension is not too large:

norms = sqrt(diag(A * A'));

Vector norm of an array of vectors in MATLAB

You can compute the norm of each column or row of a matrix yourself by using element-wise arithmetic operators and functions defined to operate over given matrix dimensions (like SUM and MAX). Here's how you could compute some column-wise norms for a matrix M:

twoNorm = sqrt(sum(abs(M).^2,1)); %# The two-norm of each column
pNorm = sum(abs(M).^p,1).^(1/p);  %# The p-norm of each column (define p first)
infNorm = max(M,[],1);            %# The infinity norm (max value) of each column

These norms can easily be made to operate on the rows instead of the columns by changing the dimension arguments from ...,1 to ...,2.