Find indices in a structure array by comparing the name

145 ビュー (過去 30 日間)
Gerhard Weiss
Gerhard Weiss 2020 年 12 月 1 日
コメント済み: Ameer Hamza 2020 年 12 月 2 日
I have struct array that is similar like that:
Block.name= {'Time','Signal_x','Signal_y','Signal_z'};
Block.channel(1).values= 1:10; %time vetor for all signals in this struct
Block.channel(2).values= rand(1,10); %correspoinding values of Signal_x
Block.channel(3).values= rand(1,10); %correspoinding values of Signal_y
Block.channel(4).values= rand(1,10); %correspoinding values of Signal_z
Now I want to pick out the values of a certain signal, assuming I know the name of the signal but I don't know the order of channels.
Name_desiredSignal= 'Signal_y'; %e.g. values of the Signal_y
I know I can do this by a loop like this:
for idx=2:length(Block.name) %I know that the first channel is always the time vector
if(strcmp(Block.name(idx),Name_desiredSignal))
channel_Nr= idx;
end
Once I have the channel number/index, I can easily get it:
desiredSignal= Block.channel(channel_Nr).values;
I wonder if there is a smarter way, which avoids the loop?
Thanks for help!

採用された回答

Ameer Hamza
Ameer Hamza 2020 年 12 月 1 日
That for-loop is same as
channel_Nr = find(contains(Block.name, Name_desiredSignal));

その他の回答 (1 件)

Gerhard Weiss
Gerhard Weiss 2020 年 12 月 2 日
Unfortunately, I noticed afterwards that my struct array in my real code is different as I wrote above.
Actually it looks like this:
%Block.name= {'Time','Signal_x','Signal_y','Signal_z'}; % wrong simplification
Block.channel(1).name= 'Time';
Block.channel(1).values= 1:10;
Block.channel(2).name= 'Signal_x';
Block.channel(2).values= rand(1,10);
Block.channel(3).name= 'Signal_y';
Block.channel(3).values= rand(1,10);
Block.channel(4).name= 'Signal_z';
Block.channel(4).values= rand(1,10);
Name_desiredSignal= 'Signal_y';
for this struct the suggested solution by Ameer does not work (because the suggested solution was for a different probelm, I know):
channel_Nr = find(contains(Block.channel.name, Name_desiredSignal))
Error using contains (line 52)
Unrecognized parameter name 'Signal_y'. Parameter name must be 'IgnoreCase'.
but a loop works which I would like to avoid:
for idx=2:length(Block.channel)
if(contains(Block.channel(idx).name,Name_desiredSignal))
channel_Nr= idx;
end
end
Any ideas?
  3 件のコメント
Gerhard Weiss
Gerhard Weiss 2020 年 12 月 2 日
Thanks again. Works for both, my example code and my real code.
Ameer Hamza
Ameer Hamza 2020 年 12 月 2 日
I am glad to be of help!

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

カテゴリ

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

タグ

製品

Community Treasure Hunt

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

Start Hunting!

Translated by