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