Search code examples
matlabmatrixnormalize

matlab rescale matrix data to -1 to 1


Possible Duplicate:
MATLAB: how to normalize/denormalize a vector to range [-1;1]

Hi, just started using Matlab and I would like to know how to rescale the data in a matrix. I have a matrix of N rows by M columns and want to rescale the data in the columns to be between -1 and 1.

Each column contains values that vary in scale from say 0 - 10,000 to some that are between 0 and 1, the reason I want to normalise to between -1 and 1 as these values will be used in a Neural Network as input values for a transform function that is sine based.


Solution

  • Neither of the previous answers are correct. This is what you need to do:

    [rows,~]=size(A);%# A is your matrix
    colMax=max(abs(A),[],1);%# take max absolute value to account for negative numbers
    normalizedA=A./repmat(colMax,rows,1);
    

    The matrix normalizedA will have values between -1 and 1.

    Example:

    A=randn(4)
    
    A =
    
       -1.0689    0.3252   -0.1022   -0.8649
       -0.8095   -0.7549   -0.2414   -0.0301
       -2.9443    1.3703    0.3192   -0.1649
        1.4384   -1.7115    0.3129    0.6277
    
    normalizedA = 
    
       -0.3630    0.1900   -0.3203   -1.0000
       -0.2749   -0.4411   -0.7564   -0.0347
       -1.0000    0.8006    1.0000   -0.1906
        0.4885   -1.0000    0.9801    0.7258