Title: MatLab accumarray unexpectedly changing ordering
Tags: matlab;grouping;accumulate;accumarray
Question: As long as I understood accumarray, it means "Making the nth row of the output: 1) find n in sub. 2) if n is in m1, m2, m3 th element in sub, 3) apply the function to m1,m2,m3 th element of val 4) that's the nth row of the output"
Am I wrong somewhere?
I ran the following code.
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)
r2 = accumarray(subs, vals', [], @(x){x'})
2    10    13
1    11    14
1    12    10
vals =
subs =
[1x4 double]
[1x2 double]
12    11    14    10
13    10
=========================
But I expected r{1} = 11 14 12 10, and r{2} = 10 13.
Why did accumarray suddenly changed the ordering?
How can I get the expected result?

Here is the accepted answer: 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'})
And running this code returns:
11    14    12    10
10    13
Comment for this answer: @LuisMendo You have become the please-_accept_-the-accepted-answer police, and I like it!
Comment for this answer: Where sorted is meant in the [linear indexing](http://www.mathworks.com/help/matlab/math/matrix-indexing.html#f1-85511) sense if you have multiple-column `subs`.
For details see [this question](http://stackoverflow.com/questions/17536558/) I recently asked.
Comment for this answer: @Mohsen_Nosratinia  Thank you! This works. I will vote for your answer once I reach enough reputation.


{'source': 'StackExchangeDataset', 'subset': 'stackoverflow.com', 'metadata': {'AnswerCount': 1, 'CommentCount': 0, 'ContentLicense': 'CC BY-SA 3.0', 'CreationDate': '2013:00:07/21/13', 'FavoriteCount': 1.0, 'PostTypeId': 1, 'Tags': '<matlab><grouping><accumulate><accumarray>', 'Title': 'MatLab accumarray unexpectedly changing ordering', 'ViewCount': 318, 'id': 17774015, 'user_AboutMe': None, 'user_AccountId': 2075715.0, 'user_DisplayName': 'user1849133', 'user_Reputation': 527.0, 'user_Views': 35.0, 'user_id': 1849133.0}}