How to select fields of a struct that contains certain string?
24 views (last 30 days)
Show older comments
I have created a trial table of 1x300 struct with 1 field, and within every struct, there are five fields.
for every struct, there is one string in massage that is either 1 or 2, which indicates the type of the struct.
How can I select the structs that only have 1 in there? Thank you.
the table is attached.
2 Comments
Matt J
on 7 Feb 2023
It would advisable for you to avoid refering to variables as "tables" unless they really are Matlab table variables.
Accepted Answer
Voss
on 7 Feb 2023
Maybe something along these lines:
load table
selected = [];
for ii = 1:numel(trial_table)
msg = {trial_table(ii).trial.message};
idx = strcmp(msg,'1');
selected = [selected trial_table(ii).trial(idx)];
end
disp(selected);
5 Comments
Voss
on 7 Feb 2023
Edited: Voss
on 7 Feb 2023
You're welcome!
Note that I made selected a cell array because I assume you want to keep the trials separated (i.e., each cell of selected contains a struct array representing one trial), but if that's not the case, you can make selected itself a struct array:
load table
selected_trial_idx = [];
for ii = 1:numel(trial_table)
msg = {trial_table(ii).trial.message};
idx = strcmp(msg,'1');
if any(idx)
selected_trial_idx(end+1) = ii;
end
end
selected = [trial_table(selected_trial_idx).trial]; % use [] instead of {}
disp(selected);
See Also
Categories
Find more on Structures in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!