Normalize matrix rows so their norm is 1 (MATLAB)

I have the following problem: I have a 16x22440 matrix A

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

How can I achieve this in matlab?

Edit: Each row in this matrix is ​​a vector created from a 160x140 image and therefore should be considered separately. Values ​​must be normalized to create a matrix of eigenvectors.

+4
source share
2 answers

Does your Matlab installation have a neural network toolbar? If so, try normr :

 nA = normr(A); 

Otherwise, @Shai solution is good, except that it will not process infinite or NaN inputs - it is much safer to check normal cases after undefined:

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

Note that normalization of zero length (all zero components) or a vector of infinite length (one or more components +Inf or -Inf ) or one with the NaN component is not very clearly defined. The solution above returns everything, as normr Matlab normr function. However, the Matlab norm function exhibits a different behavior. You can specify other behavior, such as a warning or error, all zeros, NaNs, components scaled by the length of the vector, etc. This thread discusses to some extent the problem for vectors with zero length: How do you normalize a zero vector? .

+3
source

First, calculate the norm (I assume here the Euclidean norm)

 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 
+3
source

Source: https://habr.com/ru/post/1480338/


All Articles