开发者

How to have normalize data around the average for the column in MATLAB?

开发者 https://www.devze.com 2023-01-10 14:53 出处:网络
I am trying to take a matrix and normalize the values in each cell around the average for that co开发者_开发问答lumn. By normalize I mean subtract the value in each cell from the mean value in that co

I am trying to take a matrix and normalize the values in each cell around the average for that co开发者_开发问答lumn. By normalize I mean subtract the value in each cell from the mean value in that column i.e. subtract the mean for Column1 from the values in Column1...subtract mean for ColumnN from the values in ColumnN. I am looking for script in Matlab. Thanks!


You could use the function mean to get the mean of each column, then the function bsxfun to subtract that from each column:

M = bsxfun(@minus, M, mean(M, 1));

Additionally, starting in version R2016b, you can take advantage of the fact that MATLAB will perform implicit expansion of operands to the correct size for the arithmetic operation. This means you can simply do this:

M = M-mean(M, 1);


Try the mean function for starters. Passing a matrix to it will result in all the columns being averaged and returns a row vector.

Next, you need to subtract off the mean. To do that, the matrices must be the same size, so use repmat on your mean row vector.

a=rand(10);
abar=mean(a);
abar=repmat(abar,size(a,1),1);
anorm=a-abar;

or the one-liner:

anorm=a-repmat(mean(a),size(a,1),1);


% Assuming your matrix is in A
m = mean(A);
A_norm = A - repmat(m,size(A,1),1)


As has been pointed out, you'll want the mean function, which when called without any additional arguments gives the mean of each column in the input. A slight complication then comes up because you can't simply subtract the mean -- its dimensions are different from the original matrix.

So try this:

a = magic(4)
b = a - repmat(mean(a),[size(a,1) 1]) % subtract columnwise mean from elements in a

repmat replicates the mean to match the data dimensions.

0

精彩评论

暂无评论...
验证码 换一张
取 消