MATLAB: Allocate values avoiding loop

accumarrayallocate matrixavoid loopsreshape matrix

I have the following matrix [t k p]
1.0000 1.0000 -1.1471
1.0000 2.0000 -1.0689
2.0000 1.0000 -0.8095
2.0000 2.0000 -2.9443
3.0000 1.0000 1.4384
3.0000 2.0000 0.3252
and I want an additional column with the mean of p for every t, hence
1.0000 1.0000 -1.1471 -1.1080
1.0000 2.0000 -1.0689 -1.1080
2.0000 1.0000 -0.8095 -1.8769
2.0000 2.0000 -2.9443 -1.8769
3.0000 1.0000 1.4384 0.8818
3.0000 2.0000 0.3252 0.8818
I can do it with the following code
if true
%Calulate the mean
A=[t p_tk];
p_t= accumarray(A(:,[1]), A(:,2), [], @nanmean, NaN);
% allocate it to long form
p_t_long= NaN(size(t));
for d = 1:max(t)
ind= t ==d;
p_t_long(ind)= p_t(d);
end
end
However, I want to avoid loops since I have a big dataset. Can anybody help?

Best Answer

Some indexing using the first column does what you want, more efficiently than a loop or unique:
>> M = [1,1,-1.1471;1,2,-1.0689;2,1,-0.8095;2,2,-2.9443;3,1,1.4384;3,2,0.3252]
M =
1.00000 1.00000 -1.14710
1.00000 2.00000 -1.06890
2.00000 1.00000 -0.80950
2.00000 2.00000 -2.94430
3.00000 1.00000 1.43840
3.00000 2.00000 0.32520
>> V = accumarray(M(:,1),M(:,3),[],@mean)
V =
-1.10800
-1.87690
0.88180
>> M(:,4) = V(M(:,1))
M =
1.00000 1.00000 -1.14710 -1.10800
1.00000 2.00000 -1.06890 -1.10800
2.00000 1.00000 -0.80950 -1.87690
2.00000 2.00000 -2.94430 -1.87690
3.00000 1.00000 1.43840 0.88180
3.00000 2.00000 0.32520 0.88180