Question regarding loop with multiple string comparisons?

8 ビュー (過去 30 日間)
bio lim
bio lim 2015 年 6 月 30 日
コメント済み: bio lim 2015 年 7 月 1 日
Hello. I am trying to extract several Aircraft data from a general data I have. I want the following 6 aircraft data from my general structure data. If it were for only 1 aircraft type, it works fine. However, for several aircraft, it doesn't. I am using a method such that my field 'type' matches the aircraft types and extract those data. If I use & instead of |, it also doesn't work. ( I believe it suggests that both conditions must be satisfied if I use '&' which doesn't make sense since each array has only 1 type.)
idx_plane = false(length(data2),1);
for p = 1 : length(data2) % 1574
if strcmp(data2(p).type, 'A319') | strcmp(data2(p).type, 'A318') | strcmp(data2(p).type, 'B788') | strcmp(data2(p).type, 'A320') | strcmp(data2(p).type, 'A321') | strcmp(data2(p).type, 'A330')
idx_plane(p) = true;
end
end
data2 = data2(idx_plane);
  3 件のコメント
the cyclist
the cyclist 2015 年 6 月 30 日
Perhaps an even neater way to define the index:
idx_plane = ismember({data2.type},{'A319', 'A318', 'B788', 'A320', 'A321', 'A330'});
bio lim
bio lim 2015 年 7 月 1 日
Thanks guys. It helped a lot!

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

採用された回答

the cyclist
the cyclist 2015 年 6 月 30 日
I created some made-up data, and ran your code:
data2(1).type = 'A318';
data2(2).type = 'A319';
data2(3).type = 'B318';
data2(4).type = 'B319';
data2(5).type = 'C318';
data2(6).type = 'C319';
data2(7).type = 'D318';
data2(8).type = 'D319';
idx_plane = false(length(data2),1);
for p = 1 : length(data2) % 1574
if strcmp(data2(p).type, 'A319') | strcmp(data2(p).type, 'A318') | strcmp(data2(p).type, 'B788') | strcmp(data2(p).type, 'A320') | strcmp(data2(p).type, 'A321') | strcmp(data2(p).type, 'A330')
idx_plane(p) = true;
end
end
data2 = data2(idx_plane);
It behaved as I expected. I end up with a 1x2 struct, with only the A318 and A319 types.
  1 件のコメント
bio lim
bio lim 2015 年 6 月 30 日
Oh it's working. Great then! Thanks haha.

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by