Search code examples
matlabvectormatrixnormalization

How to normalize a matrix of 3-D vectors


I have a 512x512x3 matrix that stores 512x512 there-dimensional vectors. What is the best way to normalize all those vectors, so that my result are 512x512 vectors with length that equals 1?

At the moment I use for loops, but I don't think that is the best way in MATLAB.


Solution

  • If the vectors are Euclidean, the length of each is the square root of the sum of the squares of its coordinates. To normalize each vector individually so that it has unit length, you need to divide its coordinates by its norm. For that purpose you can use bsxfun:

    norm_A = sqrt(sum(A .^ 2, 3)_;   %// Calculate Euclidean length
    norm_A(norm_A < eps) == 1;       %// Avoid division by zero
    B = bsxfun(@rdivide, A, norm_A); %// Normalize
    

    where A is your original 3-D vector matrix.

    EDIT: Following Shai's comment, added a fix to avoid possible division by zero for null vectors.