Truncate a two dim array based on contents of a particular column

4 ビュー (過去 30 日間)
Oindri
Oindri 2019 年 12 月 12 日
編集済み: Ridwan Alam 2019 年 12 月 12 日
I have an array whose number of rows can vary but cols are 34. One of the cols, 12th, has values 0,1,2 & 3. There is no set pattern as to how many times any of them can occur in one such array. Also, there is no exact distribution of rows with 12th col = 0/1/2/3, it may happen that 4 rows have 0, next 10 rows have 1, next 7 rows have 2 and last three rows have 3. My requirement is, how to truncate the array based on 12th col value being, either 0 or 1 or 2 or 3. Any help is appreciated !
  2 件のコメント
JESUS DAVID ARIZA ROYETH
JESUS DAVID ARIZA ROYETH 2019 年 12 月 12 日
could you give us a little example with desired input and output ?
Guillaume
Guillaume 2019 年 12 月 12 日
Is the aim to split the array into arrays based on the values in column 12?

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

回答 (1 件)

Ridwan Alam
Ridwan Alam 2019 年 12 月 12 日
N = input('Number of rows: ');
A = rand(N,34);
A(:,12) = randi([0 3],N,1);
% simple version if 12th col only always has 0,1,2,3
A0 = A(A(:,12)==0,:);
A1 = A(A(:,12)==1,:);
A2 = A(A(:,12)==2,:);
A3 = A(A(:,12)==3,:);
% for a more general version, use unique() on 12th col and do it in a loop for simplicity
Hope this helps!
  2 件のコメント
Guillaume
Guillaume 2019 年 12 月 12 日
Even for just 4 categories, don't do that!
You're just encouraging bad programming patterns with your numbered variables and you can be sure that at some point there'll be more categories and the same pattern will continue to be used.
g = findgroups(A(:, 12)); %group identical elements of column 12
split = splitapply(@(rows) {A(rows)}, (1:size(A, 1))', g); %split A into cell array according to group
is simpler anyway.
Ridwan Alam
Ridwan Alam 2019 年 12 月 12 日
編集済み: Ridwan Alam 2019 年 12 月 12 日
Indeed. I was trying to go there with the lead to using unique().
Also, I was just trying to answer as "simply" as possible, given "simple" is relative. :)

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

カテゴリ

Help Center および File ExchangeResizing and Reshaping Matrices についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by