MatLab accumarray unexpectedly changing ordering

风格不统一 提交于 2019-11-27 09:36:31
Mohsen Nosratinia

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!