Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
685 views
in Technique[技术] by (71.8m points)

matlab - Grouping matrix rows in terms of one column

First of all it is really hard for me to describe the problem really good but I'll try.

Say that we have matrix A

A = [23 1;
     45 1
     78 1
     86 1
     98 2
     1  2
     23 2
     14 3
     15 4
     85 4]

What I want as an output is

    B{1} = [23,45,78,86]
    B{2} = [98,1,23]
    B{3} = [14]
    B{4} = [15,85]

Bear in mind that the original A is a huge matrix, and I do not wanna do this with for loops. I would like to use functions that uses parallel processing.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.8k users

...