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

17 ビュー (過去 30 日間)
Kish1794
Kish1794 2018 年 8 月 31 日
コメント済み: Kish1794 2018 年 8 月 31 日
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 件のコメント
madhan ravi
madhan ravi 2018 年 8 月 31 日
I mean the strict file so that it can be tested?
Kish1794
Kish1794 2018 年 8 月 31 日
Uploaded

サインインしてコメントする。

採用された回答

Stephen23
Stephen23 2018 年 8 月 31 日
編集済み: Stephen23 2018 年 8 月 31 日
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.

その他の回答 (1 件)

Robert U
Robert U 2018 年 8 月 31 日
編集済み: Robert U 2018 年 8 月 31 日
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 件のコメント
Robert U
Robert U 2018 年 8 月 31 日
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 2018 年 8 月 31 日
Thanks Robert U.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeCharacters and Strings についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by