matlab rescale matrix data to -1 to 1 [duplicate]

百般思念 提交于 2019-12-01 14:53:58

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

A simple solution would use simple logic. Assuming that you mean to scale EACH column independently, do this:

  1. Subtract off the column minimum for each column.
  2. Scale the column maximum to be 2.
  3. Subtract 1.

Clearly this will result in the min for each column to be -1, the max will be 1. Code to do so is simple enough.

A = randn(5,4)   % some random example data
A =
    0.70127      0.20378       0.4085      0.83125
    0.64984     -0.90414      0.67386       1.2022
     1.6843      -1.6584     -0.31735      -1.8981
    -1.3898     -0.89092     -0.23122      -1.2075
    0.72904    -0.095776      0.67517      0.28613

Now, perform the steps above to A.

A = bsxfun(@minus,A,min(A,[],1));
A = bsxfun(@times,A,2./max(A,[],1));
A = A - 1

A =
    0.36043            1      0.46264      0.76071
    0.32697     -0.18989      0.99735            1
          1           -1           -1           -1
         -1      -0.1757     -0.82646     -0.55446
     0.3785      0.67828            1      0.40905
[m, n] = size(normalizedMatrix)
normalizedMatrix*2-ones(m,n)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!