Place equal elements in cell array

旧街凉风 提交于 2019-12-12 05:24:56

问题


I have an array. I sorted it, so I have sorted array and indeces of sorted elements in the initial array.

Fo example, from [4 5 4 4 4 4 5 4] I got [4 4 4 4 4 4 5 5] and [1 3 4 5 6 8 2 7].

How to place recieved indeces in a cell array, so that in one cell will be indeces of equal elements? For my example, it will be: {1 3 4 5 6 8}, {2 7}.

I'm searching for non-loop way to solve it.


回答1:


Use accumarray:

x = [4 5 4 4 4 4 5 4]; %// data

[~, ~, jj] = unique(x);
result = accumarray(jj(:), 1:numel(x), [], @(v) {v(:).'});

Or, if you need each set of indices sorted:

result = accumarray(jj(:), 1:numel(x), [], @(v) {sort(v(:)).'});


来源:https://stackoverflow.com/questions/22426139/place-equal-elements-in-cell-array

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