MATLAB: How to compare string array with the names of structure’s fields.

getfieldstringstructures

I have a structure with 12 fields and a string array named variables containing 4 values. I want to compare all values in my string arrays with the names of my structure fields, and if the fields' name and the string value were the same, return values of that field as an output. I try strcmp command to compare my string array with the fields' name in a for loop.(for i = 1:numel(variables)) then I use switch and case but I have no idea how to return the field values as an output when the statement is true. (I think I should use getfield command but I don't know how). could you please help me in this regard. thank you.

Best Answer

S.a = {'First field'};
S.b = {'Second field, entry 1','Second field,entry 2'};
S.c = {1,2,3};
mystring = {'a','game','matlab','c'};
[~,indx] = ismember(fieldnames(S),mystring);
all = arrayfun(@(x) getfield(S,mystring{x}),indx(indx>0),'un',0);
all{:} =
{'First field'}
{[1]} {[2]} {[3]}