Vector norm of an array of vectors in MATLAB

Amelio Vazquez-Reina picture Amelio Vazquez-Reina · Aug 26, 2011 · Viewed 21.4k times · Source

When calling norm on a matrix in MATLAB, it returns what's known as a "matrix norm" (a scalar value), instead of an array of vector norms. Is there any way to obtain the norm of each vector in a matrix without looping and taking advantage of MATLAB's vectorization?

Answer

gnovice picture gnovice · Aug 26, 2011

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.