Spencer
Spencer

Reputation: 41

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

I am trying to take a matrix and normalize the values in each cell around the average for that column. 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!

Upvotes: 3

Views: 7025

Answers (4)

gnovice
gnovice

Reputation: 125854

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);

Upvotes: 10

Doresoom
Doresoom

Reputation: 7448

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);

Upvotes: 3

Matt Mizumi
Matt Mizumi

Reputation: 1193

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.

Upvotes: 1

Alejandro
Alejandro

Reputation: 1034

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

Upvotes: 1

Related Questions