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