Vector norm of an array of vectors in MATLAB
Solution 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
.
Solution 2
From version 2017b onwards, you can use vecnorm.
Solution 3
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).
Solution 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
Amelio Vazquez-Reina
I'm passionate about people, technology and research. Some of my favorite quotes: "Far better an approximate answer to the right question than an exact answer to the wrong question" -- J. Tukey, 1962. "Your title makes you a manager, your people make you a leader" -- Donna Dubinsky, quoted in "Trillion Dollar Coach", 2019.
Updated on July 05, 2022Comments
-
Amelio Vazquez-Reina almost 2 years
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? -
Amro over 12 yearsmaybe you should explicitly specify the dimensions along which SUM and MAX operate, that way it would be easier to switch to row-wise norms...
-
gnovice over 12 years@Amro: Good suggestion. Done!
-
kroimon almost 11 yearsIf
M
consists of real numbers only, you can replace theabs(M)
withM
in thetwoNorm
as the.^2
effectively cancels out any negative signs. -
user877329 over 10 yearsIf M contains any non-real number, you may want to M.*conj(M) instead
-
Jommy over 9 yearsFor the two-norm you can also use
sqrt(dot(M, M, dim))
. -
WillC almost 6 yearsSlight addition:
norm_2 = @(A,dim)sqrt( sum( real(A).*conj(A) , dim) )
allows forB=magic([2,3])
andnorm_2( B , 1)
ornorm_2( B , 2)
.