how to compare string array with the names of structure's fields.

25 Ansichten (letzte 30 Tage)
Sara
Sara am 2 Jul. 2018
Kommentiert: Sara am 3 Jul. 2018
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.
  1 Kommentar
Adam
Adam am 2 Jul. 2018
You can use dynamic strings to get data out of a struct field e.g.
str = 'SomeStructFieldName';
value = myStruct.( str );

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

Paolo
Paolo am 2 Jul. 2018
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]}
  3 Kommentare
Paolo
Paolo am 3 Jul. 2018
T = table(all{:});
T.Properties.VariableNames = mystring(indx(indx>0));
T =
1×2 table
a c
_____________ _________________
'First field' [1] [2] [3]

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (1)

Stephen23
Stephen23 am 3 Jul. 2018
Bearbeitet: Stephen23 am 3 Jul. 2018
I would use struct2cell to get a cell array, then used basic MATLAB indexing to obtain the "fields" (rows of the cell array) that you want. Using a cell array makes it easy to use cell2table to generate a table from the cell array and the fieldnames:
>> S.a = '1st';
>> S.b = {'2ndOne','2ndTwo'};
>> S.c = 3;
>> F = fieldnames(S);
>> C = struct2cell(S);
>> lookfor = {'a','hello','world','c'};
>> [idx,idy] = ismember(lookfor,F);
>> idz = idy(idx)
>> T = cell2table(C(idz,:),'VariableNames',F(idz))
  3 Kommentare
Stephen23
Stephen23 am 3 Jul. 2018
Bearbeitet: Stephen23 am 3 Jul. 2018
@Sahar: you are right, I think the first input needs to be transposed:
Table = cell2table(Cell(indz,:).','VariableNames',Fname(indz));
According to the cell2table help "Each column of C provides data for a table variable", whereas struct2cell returns one row for each field, so a transpose is required.
Sara
Sara am 3 Jul. 2018
Many Thanks for your help.

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Data Type Conversion 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