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

16 vues (au cours des 30 derniers jours)
Kish1794
Kish1794 le 31 Août 2018
Commenté : Kish1794 le 31 Août 2018
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 commentaires
madhan ravi
madhan ravi le 31 Août 2018
I mean the strict file so that it can be tested?

Connectez-vous pour commenter.

Réponse acceptée

Stephen23
Stephen23 le 31 Août 2018
Modifié(e) : Stephen23 le 31 Août 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.

Plus de réponses (1)

Robert U
Robert U le 31 Août 2018
Modifié(e) : Robert U le 31 Août 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 commentaires
Robert U
Robert U le 31 Août 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.
Kish1794
Kish1794 le 31 Août 2018
Thanks Robert U.

Connectez-vous pour commenter.

Catégories

En savoir plus sur Characters and Strings dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by