How to divide a structure into sub-structures based on a condition

37 ビュー (過去 30 日間)
SS
SS 2019 年 7 月 24 日
回答済み: Joel Handy 2019 年 7 月 25 日
Hello.
I am new to MATLAB and expecting some help. I have a structure array (1 x 50,000) with 30 fields. I want to divide this structure into multiple structures based on a condition.
I tried sometheing like this. Let the main structure be vel and it has 30 fields. Based on the values of the parameters in the field y of the structure vel, I want to create sub-structures.
for i=1:length(vel)
if y<=20
vel_sub1(i)=vel(i) % creating a new structure
else
vel_sub(i)=[] % null
end
if y>=20 && y<=100
vel_sub2(i)=vel(i) % creating another sub-structure
else
vel_sub(2)=[] % null
end
end
But, unfortunatley I am getting some empty fields in the sub-structure, is there any smart way to implement this without any empty rows in the fields?
  4 件のコメント
Walter Roberson
Walter Roberson 2019 年 7 月 25 日
Is the desired result 1 x 50000 struct with two fields, each of which is a scalar struct with 30 fields?
Or is the desired result a scalar struct with two fields, one of which is a 1 x something struct array of 30 fields and the other is 1 x (50000 minus something) struct array of 30 fields?
SS
SS 2019 年 7 月 25 日
Hi. It is the second one.

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

採用された回答

Walter Roberson
Walter Roberson 2019 年 7 月 25 日
mask = [vel.y] <= 20;
result.vel_sub1 = vel(mask) ;
result.vel_sub2 = vel(~mask) ;

その他の回答 (1 件)

Joel Handy
Joel Handy 2019 年 7 月 25 日
I think this is what you are looking for. You will end up with two struture arrays both smaller than the original structure array in the number of elements and the number of fields.
sub1Fields = {'Field1', 'Field3', 'Field5'};
sub2Fields = {'Field2', 'Field4', 'Field6'};
vel_sub1 = vel([vel,y] < 20);
vel_sub1 = rmfield(vel_sub1,sub2Fields);
vel_sub2 = vel([vel,y] >= 20);
vel_sub2 = rmfield(vel_sub1,sub1Fields);

カテゴリ

Help Center および File ExchangeStructures についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by