Grouping matrix rows in terms of one column

别来无恙 提交于 2019-11-28 13:59:39

You could use accumarray here:

B = accumarray(A(:,2),A(:,1),[],@(x){x},{});

If you know that A is sorted, and that there is no missing entry from the second column, you can also use mat2cell:

counts = histc(A(:,2),unique(A(:,2)));
B = mat2cell(A(:,1),counts);

Here's a simple way to do it. It uses a loop, but should be pretty quick because the cell array B is pre-allocated using the reverse index trick.

for key = fliplr(unique(A(:,2)'))
    ndx = A(:,2) == key;
    B{key} = A(ndx,1)';
end
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!