Reputation: 127
I have a matrix with duplicate numbers in one of the columns. I would like to average the rows with duplicate numbers. For example, I have duplicate values in a matrix A
in column 3:
A =
1 2 1
4 4 2
5 4 2
4 5 2
5 5 3
10 3 3
I would like to get
B =
1 2 1
4.3333 4.3333 2.0000
7.5000 4.0000 3.0000
where each row is the average values of the duplicate rows of column 3.
Can anyone help?
Upvotes: 0
Views: 338
Reputation: 32920
The following one-liner averages all rows with duplicate values in column N
.
cell2mat(arrayfun(@(x)mean(A(A(:, N)==x,:),1), unique(A(:, N)), 'Uniform', 0))
Let's follow your example and average all lines with duplicates in column 3:
A = [1 2 1; 4 4 2; 5 4 2; 4 5 2; 5 5 3; 10 3 3];
N = 3;
B = cell2mat(arrayfun(@(x)mean(A(A(:, N)==x,:),1), unique(A(:,N)), 'Uniform', 0))
The result is:
B =
1.0000 2.0000 1.0000
4.3333 4.3333 2.0000
7.5000 4.0000 3.0000
Upvotes: 3