How to find a particular string in a stuct which has multiple fields?

11 views (last 30 days)
I want to search and get the index of the string 'mnop' in the stuct MyStruct which has two fields abc and def. Please refer to the attachment to know how the struct looks. Currently string 'mnop' exists in second row of the field MyStruct.abc.I tried using strfind, strcmp and ismember. I know i'm missing a trick somewhere. Any help would be appreciated. Thanks.
  4 Comments

Sign in to comment.

Accepted Answer

Stephen23
Stephen23 on 31 Aug 2018
Edited: Stephen23 on 31 Aug 2018
Why not something simple like this?:
>> S = load('MyStruct.mat');
>> MyS = S.MyStruct;
>> strcmp({MyS.abc},'mnop')
ans =
0 1 0 0
>> strcmp({MyS.def},'mnop')
ans =
0 0 0 0
This clearly identifies that the char vector 'mnop' exists in the second cell of the field abc. You can easily put this code into a loop, and loop over all of the fieldnames:
C = fieldnames(MyS);
for k = 1:numel(C)
strcmp({MyS.(C{k})},'mnop')
end
and within the loop use whatever logic that you require.

More Answers (1)

Robert U
Robert U on 31 Aug 2018
Edited: Robert U on 31 Aug 2018
Hi Kish1794,
you can write a function that utilizes strfind on the structure array:
main.m
%%Create TestData
abc = {'jkl','mnop','zxcv','hgfsf'};
def = {'def','tre','asd','qwerty'};
for ik = 1:numel(abc)
sIn(ik).abc = abc{ik};
sIn(ik).def = def{ik};
end
%%Call Function
[nField,nStruct] = getFieldValue(sIn,'mnop');
%%Check result
cFields = fieldnames(sIn);
Output = sIn(nStruct{1}).(cFields{nField{1}});
getFieldValue.m
function [ nField, nStruct ] = getFieldValue( sIn, strFind )
cFieldName = fieldnames(sIn);
nField = {};
nStruct = {};
for ik = 1:numel(cFieldName)
testVec = ~cellfun(@isempty,strfind({sIn.(cFieldName{ik})},strFind));
if any(testVec)
nField{end+1} = ik;
nStruct{end+1} = find(testVec);
end
end
end
  3 Comments
Robert U
Robert U on 31 Aug 2018
That's exactly what it returns. You get a clear index of the string to find comprising index of structure array and index of cell.
You can even handle strings that occur several times over your structure and it does not matter what name you chose for field names.

Sign in to comment.

Categories

Find more on Characters and Strings 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!