Vector norm of an array of vectors in MATLAB

2019-01-11 13:13发布

问题:

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?

回答1:

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.



回答2:

The existing implementation for the two-norm can be improved.

twoNorm = sqrt(sum(abs(M).^2,1)); # The two-norm of each column

abs(M).^2 is going to be calculating a whole bunch of unnecessary square roots which just get squared straightaway.

Far better to do:

twoNorm = sqrt( 
               sum( real(M .* conj(M)),  1 )
              )

This efficiently handles real and complex M.

Using real() ensures that sum and sqrt act over real numbers (rather than complex numbers with 0 imaginary component).



回答3:

From version 2017b onwards, you can use vecnorm.



回答4:

Slight addition to P i's answer:

norm_2 = @(A,dim)sqrt( sum( real(A).*conj(A) , dim) )

allows for

B=magic([2,3])
norm_2( B , 1)
norm_2( B , 2)

or as this if you want a norm_2.m file:

function norm_2__ = norm_2 (A_,dim_)
    norm_2__ = sqrt( sum( real(A_).*conj(A_) , dim_) )  ;
end