开发者

Vector norm of an array of vectors in MATLAB

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 m开发者_如何转开发atrix without looping and taking advantage of MATLAB's vectorization?


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.


From version 2017b onwards, you can use vecnorm.


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).


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜