splitting matrix based on a value in one column

Hi All,
I have a very large matrix part of which looks like this:
7 0
10 0
16 0
19 1
26 1
29 1
3 1
5 0
69 0
36 0
78 0
as you can see, the second column is either 0 or 1. I want to split this large matrix into sub matrices such that each sub matrix represent only the parts where the second column is 0. How do we do this? Thanks.

 採用された回答

Stephen23
Stephen23 2017 年 6 月 17 日
編集済み: Stephen23 2017 年 6 月 17 日

10 投票

Hard-coded indexing:
>> M = [7,0;10,0;16,0;19,1;26,1;29,1;3,1;5,0;69,0;36,0;78,0];
>> M(M(:,2)==0,:)
ans =
7 0
10 0
16 0
5 0
69 0
36 0
78 0
>> M(M(:,2)==1,:)
ans =
19 1
26 1
29 1
3 1
General solution:
>> [~,~,X] = unique(M(:,2));
>> C = accumarray(X,1:size(M,1),[],@(r){M(r,:)});
>> C{1}
ans =
7 0
10 0
16 0
36 0
69 0
78 0
5 0
>> C{2}
ans =
26 1
19 1
29 1
3 1

7 件のコメント

Thomas Booij
Thomas Booij 2018 年 6 月 16 日
Thanks a lot!
Aleem Akhtar
Aleem Akhtar 2018 年 9 月 30 日
That was great solution. You saved day for me.
Sandeep  Karthikeyan
Sandeep Karthikeyan 2019 年 8 月 7 日
Thanks a lot for the answer.
Joshua
Joshua 2020 年 7 月 8 日
編集済み: Joshua 2020 年 7 月 8 日
Great solution! How would you do this for the transpose of M? I.e. if I had the array M' and wanted to sort the columns into a cell matrix of arrays?
Chris Stillo
Chris Stillo 2020 年 12 月 15 日
Thank god someone knows what they are doing!
Pol Medir
Pol Medir 2021 年 2 月 22 日
How would you do this if the sample of data was too large to input manually?
Stephen23
Stephen23 2021 年 2 月 22 日

サインインしてコメントする。

その他の回答 (1 件)

123456
123456 2018 年 7 月 18 日

0 投票

How could I do the same thing but divide cell array by strings from one row? Let's say, that the array looks like that:
t2 1 2
t2 2 3
t1 3 4
t2 4 5
t1 5 6
t1 6 7
I would like to recieve two arrays at the end:
1 2
2 3
4 5
and
3 4
5 6
6 7

1 件のコメント

Stephen23
Stephen23 2018 年 7 月 19 日
There are several solutions. One way is to input the first column into unique, and use its third output with my answer.

サインインしてコメントする。

カテゴリ

ヘルプ センター および File ExchangeMatrices and Arrays についてさらに検索

質問済み:

2017 年 6 月 17 日

コメント済み:

2021 年 2 月 22 日

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by