# How to subtract mean along rows?

6 Ansichten (letzte 30 Tage)
JFz am 5 Jan. 2018
Kommentiert: JFz am 8 Jan. 2018
Hi,
I have a matrix 100x120 and I can group along the rows by findgroups. Then I use mean_mat = splitapply(@mean, mat, G) to get the means along rows. How to subtract the mean from the original matrix from each group? That is: for each group I, get mat_i - mean_mat_i? Thanks.
##### 0 Kommentare-2 ältere Kommentare anzeigen-2 ältere Kommentare ausblenden

Melden Sie sich an, um zu kommentieren.

### Akzeptierte Antwort

Manan Mishra am 8 Jan. 2018
One way to do this would be following:
When you operate on each individual row for finding groups using "findgroups" and mean using "splitapply", you can then use the variable "G" to separate the elements belonging to a specific group and subtract the group mean from each element.
For example,
if 'x' is my 100x120 matrix and x_r is a particular row I am operating on, after using these commands:
>> G = findgroups(x_r);
>> mean_mat = splitapply(@mean,x_r,G);
I can subtract the group mean from each element of that group by using the following commands:
>> x_r(G == 1) = x_r(G == 1) - mean_mat(1);
>> x_r(G == 2) = x_r(G == 2) - mean_mat(2);
.
.
.
If the number of groups are small, you can write these commands separately for each group. Otherwise, you can write a loop to do this for each group:
for(i = 1:max(G))
x_r(G == i) = x_r(G == i) - mean_mat(i);
end
##### 1 Kommentar-1 ältere Kommentare anzeigen-1 ältere Kommentare ausblenden
JFz am 8 Jan. 2018
Thank you so much! Let me try it today. Happy New Year!

Melden Sie sich an, um zu kommentieren.

### Weitere Antworten (2)

Guillaume am 8 Jan. 2018
Bearbeitet: Guillaume am 8 Jan. 2018
A simpler way, which does not involve loops at all, just simple indexing:
mean_mat = splitapply(@mean, mat, G);
mat_minus_mean = mat - mean_mat(sub2ind(size(mean_mat), repmat(G, 1, size(meat, 2)), repmat(1:size(mat, 2), numel(G), 1)));
The mean_mat(sub2ind(...)) simply creates a matrix the same size as mat whose row r is mean_mat(G(r), :). This is then simply subtracted from mat.
##### 1 Kommentar-1 ältere Kommentare anzeigen-1 ältere Kommentare ausblenden
JFz am 8 Jan. 2018
Thanks! I will try this one too.
If this also works. I will accept both answers. :-).

Melden Sie sich an, um zu kommentieren.

JFz am 8 Jan. 2018
I think both answers are correct but I don't know how to choose both.
##### 2 KommentareKeine anzeigenKeine ausblenden
Guillaume am 8 Jan. 2018
You cannot accept two answers (but you can vote for as many as you want).
JFz am 8 Jan. 2018
OK. I accepted one and voted for the other. Hehe.

Melden Sie sich an, um zu kommentieren.

### Kategorien

Mehr zu Logical finden Sie in Help Center und File Exchange

### Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by