Amelio Vazquez-Reina
Amelio Vazquez-Reina

Reputation: 96284

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 matrix without looping and taking advantage of MATLAB's vectorization?

Upvotes: 20

Views: 22649

Answers (4)

WillC
WillC

Reputation: 977

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

Upvotes: 1

Xaser
Xaser

Reputation: 2146

From version 2017b onwards, you can use vecnorm.

Upvotes: 9

P i
P i

Reputation: 30684

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

Upvotes: 4

gnovice
gnovice

Reputation: 125854

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.

Upvotes: 26

Related Questions