MATLAB's built-in function accumarray accepts a function fun as a fourth argument.
A = accumarray(subs,val,sz,fun);
This applies fun to each subset of elements in val that have identical subscripts in subs. The documentation however states:
If the subscripts in
subsare not sorted with respect to their linear indices,funshould not depend on the order of the values in its input data.
How can we implement a stable version of accumarray, which doesn't have this limitation, but will guarantee that the subsets adopt the same order as given by val?
Example:
subs = [1:10,1:10];
val = 1:20;
accumarray(subs(:), val(:), [], @(x)x(end)).'
The expected output of this would be 11:20 if accumarray were stable. In fact the output is:
ans =
11 12 13 14 5 6 7 18 19 20
Our implementation should yield:
accumarrayStable(subs(:), val(:), [], @(x)x(end)).'`
ans =
11 12 13 14 15 16 17 18 19 20