views:

53

answers:

4

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!

+1  A: 

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);
Doresoom
+6  A: 

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));
gnovice
how would I switch it around to do mean of rows
Spencer
@Spencer: You just have to add a `,2` to the call to MEAN in order to subtract the row means from each row, like so: `M = bsxfun(@minus,M,mean(M,2));`
gnovice
+1 for bsxfun (weirdest name i've seen in a while for a useful function!)
Jason S
@Jason S: bsx stands for binary singleton expansion
Amro
+1  A: 
% Assuming your matrix is in A
m = mean(A);
A_norm = A - repmat(m,size(A,1),1)
Alejandro
Um, the question was apparently to subtract off the mean value. Your answer DIVIDES by the mean. Yes, the word normalize was used, but it was explicitly defined.
woodchips
+1  A: 

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.

Matt Mizumi

related questions