MATLAB: I find a problem about accumarray​(subs,val,​[],@(x)sum​(diff(x)))​, maybe a bug

accumarray bug

in the example of function accumarray, when use the diff ,it's so weird that the index of the val ,sometime the input value of x is Positive order ,but sometime is Reverse order,(u can run the code ,then pay attention to the value of y(the input value of x)),in the B3,u can get y(the input of diff ) like this
y =
103
y =
104
106
y =
102
101
it's so weird that 104 106 and 102 101,why it's not 101 102 ,it will lead to a wrong diff .
the code followed :
clc;clear all;
val = [101 102 103 104 105 106];
subs=[1 2; 1 2; 3 1; 4 1; 4 4; 4 1];
B1 = accumarray(subs,val,[],@(x)sum(my(x)))
B2 = accumarray(subs,val,[],@(x)sum(my(diff(x))))
subs= [1 2; 3 1; 1 2; 4 4; 4 1; 4 1;];
B3 = accumarray(subs,val,[],@(x)sum(my(x)))
B4 = accumarray(subs,val,[],@(x)sum(my(diff(x))))
function [ y] = my( x )
y=x
end

Best Answer

When the 'subs' values are not in what Mathworks considers as "sorted order", the 'accumarray' algorithm calls for some kind of sorting operation to place 'subs' in sorted order, and it subsequently reorders the 'val' vector accordingly. However, apparently the sorting operation which is used does not necessarily behave in the same way Mathworks' own 'sort' function does with respect to equal entries. For equal entries, matlab's 'sort' operation guarantees that the corresponding sort indices are a sequence of successively increasing integers. That is, if one does
[B,IX] = sort([7,7,4]);
the value for IX is guaranteed to be [3,1,2] and never [3,2,1]. Such is apparently not true for whatever sorting method Mathworks is using with 'accumarray'. Sometimes the index order for equal entries is reversed as apparently happens in their Example 2 in which the indexing is reversed for the two [1,2] equal entries, leading to a sequence of 'val' values of 102,101 instead of the expected 101,102. It would be interesting to find out just what sorting algorithm Mathworks is using in 'accumarray' that it produces such reversals for equal entries.