finding instances of a string withinin a structure
133 views (last 30 days)
Show older comments
Dear community,
I have structure which I would like to locate the instances of a certain string. The data is laid out as follows:
The variable is called
Markers which is 360x24 struct , with five fields.
The fields are:
ChannelNumber (double)
Description (which is a character/string)
Points (double)
Position (double)
Type (character/string)
Example:
What I'm trying to do is to find the index of all instances of 's2' in Description, so it's a string. I've tried modifying code which I've found on here, but it doesn't seem to work.
Just to give another example of the file layout, if I click on one of the structs containing S2 it looks like this in the workspace:
Markers(2, 2).Description
I know I need to use strcmp of strfind, but I just don't seem to be able to get the syntax right. Generally I never work with anything other than matrixes or cells, so this is a bit beyond my experience!
Hopefully someone can help please?
Best wishes, Joe
0 Comments
Accepted Answer
Jan
on 10 May 2018
Edited: Jan
on 10 May 2018
match = reshape(strcmp({Markers.Description}, 's2'), size(Markers));
Now match(i,j) is TRUE, when the struct Markers(i,j).Description is the string 's2'. If any occurrence is wanted, e.g. also "*s2*", you need:
Desc = {Markers.Description};
Desc(~cellfun('isclass', Desc, 'char')) = {''}; % Care for non-strings
matchC = reshape(strfind(Desc, 's2'), size(Markers));
match = ~cellfun('isempty', matchC);
Now match is again a logical matrix, which is TRUE, when the corresponding field contains the string 's2' anywhere.
1 Comment
More Answers (1)
Ameer Hamza
on 10 May 2018
Edited: Ameer Hamza
on 10 May 2018
The following will return a boolean array of the indexes to indicate which struct contains the required string
indexes = reshape(contains({Markers.Description}, 's2'), size(Markers))
Markers(indexes) % will return the structs containing 's2' in Description
If you are interested in the actual location of 's2' inside each string, use
reshape(strfind({Markers. Description}, 's2'), size(Markers))
3 Comments
Ameer Hamza
on 10 May 2018
Edited: Ameer Hamza
on 10 May 2018
If some description field is empty matrices [], then it will create the problem. In this case, try following
positions = arrayfun(@(x) strfind(x.Description, 's2'), Markers, 'UniformOutput', false)
boolIndex = arrayfun(@(x) ~isempty(strfind(x.Description, 's2')), Markers)
See Also
Categories
Find more on EEG/MEG/ECoG 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!