I have a matrix and would like to average all columns where column 1 has the same value. For example A [1 2 3; 1 2 5; 3 2 5] The column 1 has two times the number 1, so I would like to all columns where column 1 has number 1, so that the outcome will be A_new [1 2 4; 3 2 5]
What is the easiest way to do so?
Additionally, I would like in this matrix that every number between 1 and in this example 3, is present in column 1, and that it should fill the corresponding other columns with NaNs.
So the outcome should be A_new2 [1 2 4; 2 NaN NaN; 3 2 5]
CodePudding user response:
This is a job for splitapply
, together with findgroups
(or unique
):
A = [1 2 3; 1 2 5; 3 2 5];
[g, h] = findgroups(A(:,1)); % or [~, h, g] = unique(10*A(:,1));
result = [h splitapply(@(x)mean(x,1), A(:, 2:end), findgroups(A(:,1)))];