MatLab accumarray unexpectedly changing ordering
The documentation of accumarray says:
Note If the subscripts in
subs
are not sorted,fun
should not depend on the order of the values in its input data.
And your subs
is not sorted (at least not in ascending order). If you rewrite the code so that subs
is sorted and vals
is also rearranged accordingly you get the desired result:
A = [2 10 13 ; 1 11 14; 1 12 10]
[U,ix,iu]= unique(A(:,1))
vals = reshape(A(:, 2:end).', [], 1)
subs = reshape(iu(:, ones(size(A, 2)-1,1)).', [], 1)
[subs_sorted, I] = sort(subs);
r2 = accumarray(subs_sorted, vals(I)', [], @(x){x'})
r2{1}
r2{2}
And running this code returns:
ans =
11 14 12 10
ans =
10 13