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

15,214

Solution 1

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

Solution 2

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
Share:
15,214
Jacka
Author by

Jacka

Updated on July 07, 2022

Comments

  • Jacka
    Jacka almost 2 years

    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.