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

11 Ansichten (letzte 30 Tage)
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 Kommentare
madhan ravi
madhan ravi am 31 Aug. 2018
I mean the strict file so that it can be tested?

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

Stephen23
Stephen23 am 31 Aug. 2018
Bearbeitet: Stephen23 am 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.

Weitere Antworten (1)

Robert U
Robert U am 31 Aug. 2018
Bearbeitet: Robert U am 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 Kommentare
Robert U
Robert U am 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.

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Characters and Strings finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by