Averaging replicate data in Matlab, multiple variables

68 Views Asked by At

I'm trying to average replicate data in MATLAB and running into some difficulty. The variables are depth, Var1, Var2. Sometimes there is a replicate in Var1, sometimes there is a replicate in Var2, sometimes there is a replicate for both Var1 and Var2 for a given depth. So the matrix might look something like this:

1   0.2 1,
2   0.5 3,
2   0.7 NaN,
3   0.1 5,
3   0.7 6,
4   0.3 4,
...

depth is the unique identifier so I would like to create a matrix with [depth, Var1, Var2] that looks like this:

1   0.2 1,
2   0.6 3,
3   0.4 5.5,
4   0.3 4,
...

The function accumarray would work if I had an n-by-2 matrix, but this is n-by-3. Any recommendations on how to proceed?

2

There are 2 best solutions below

1
Gelliant On

This should work

a=[1 0.2 1; 2 0.5 3; 2 0.7 NaN; 3 0.1 5; 3 0.7 6; 4 0.3 4];
depths = unique(a(:,1));
b=nan(length(depths),3);
for ct = 1:length(depths)
    b(ct,:)=mean(a(a(:,1)==depths(ct),:),1,'omitnan');
end

result

b =

    1.0000    0.2000    1.0000
    2.0000    0.6000    3.0000
    3.0000    0.4000    5.5000
    4.0000    0.3000    4.0000
0
Leander Moesinger On

A bit naive implementation with accumarray which loops over the variables.

A = [1   0.2 1
2   0.5 3
2   0.7 NaN
3   0.1 5
3   0.7 6
4   0.3 4];

result = zeros([numel(unique(A(:,1))) size(A,2)]);
result(:,1) = unique(A(:,1));
for ii = 2:size(A,2)
    result(:,ii) = accumarray(A(:,1),A(:,ii),[],@mean);
end