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

爱⌒轻易说出口 提交于 2019-12-09 03:36:26

问题


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.


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




回答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


来源:https://stackoverflow.com/questions/16508451/normalizing-rows-of-matrix-so-that-their-norm-is-equal-to-1-matlab

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!