Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Normalizing rows of matrix, so that their norm is equal to 1 (MATLAB)

I have a following problem - I have a matrix A of size 16x22440.

What I need to do is to normalize each row of this matrix, so that the norm of each of them is equal to 1 (for n=1:16 norm(A(n,:))==1)

How can I achieve that in matlab?

Edit: Each row in this matrix is a vector created of an 160x140 image and thus must be considered separately. The values need to be normalised to create an eigenfaces matrix.

like image 626
Jacka Avatar asked Feb 17 '23 13:02

Jacka


2 Answers

First, compute the norm (I assume Eucleadian norm here)

n = sqrt( sum( A.^2, 2 ) );
% patch to overcome rows with zero norm
n( n == 0 ) = 1;
nA = bsxfun( @rdivide, A, n ); % divide by norm
like image 146
Shai Avatar answered Feb 19 '23 03:02

Shai


Does your install of Matlab include the Neural Network Toolbox? If so, then try normr:

nA = normr(A);

Otherwise, @Shai's solution is good except that it won't handle infinite or NaN inputs – it's much safer to check undefined norm cases afterwards:

nA = bsxfun(@rdivide,A,sqrt(sum(A.^2,2)));
nA(~isfinite(nA)) = 1; % Use 0 to match output of @Shai's solution, Matlab's norm()

Note that normalizing of a zero length (all zero components) or infinite length vector (one or more components +Inf or -Inf) or one with a NaN component is not really well-defined. The solution above returns all ones, just as does Matlab's normr function. Matlab's norm function, however, exhibits different behavior. You may wish to specify a different behavior, e.g., a warning or an error, all zeros, NaNs, components scaled by the vector length, etc. This thread discusses the issue for zero-length vectors to some extent: How do you normalize a zero vector?.

like image 28
horchler Avatar answered Feb 19 '23 04:02

horchler