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

17 visualizaciones (últimos 30 días)
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 comentarios
madhan ravi
madhan ravi el 31 de Ag. de 2018
I mean the strict file so that it can be tested?

Iniciar sesión para comentar.

Respuesta aceptada

Stephen23
Stephen23 el 31 de Ag. de 2018
Editada: Stephen23 el 31 de Ag. de 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.

Más respuestas (1)

Robert U
Robert U el 31 de Ag. de 2018
Editada: Robert U el 31 de Ag. de 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 comentarios
Robert U
Robert U el 31 de Ag. de 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.

Iniciar sesión para comentar.

Categorías

Más información sobre Characters and Strings en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by