How to define a structure fieldname from a cell contains a string value?

19 Ansichten (letzte 30 Tage)
Dear All:
I am having trouble to define structure fieldnames from a cell array that contains the names as string values:
select = [{'NAME'}, {'VALUE'};
{'alpha'}, 0.4;
{'sigmaL'}, 1;
{'beta'}, 0.98];
and in a loop I want to create a structure from the cell array (select) with field name as in the first column and value in the second column if certain criteria is met. I have tried setfield and struct command, but in all cases the 'fieldname' input does not like I reference to the cell array (eg: select(1,3)), and ask for a proper string within quotation marks.
I want to ask how to create a structure by referencing to cell arrays? (In my case is create something like structure.alpha = 0.4 by referencing to select?)
Thank you very much in advance for your help.
Cheers
Ben

Akzeptierte Antwort

Matt Fig
Matt Fig am 24 Apr. 2011
Instead of using EVAL, use dynamic fieldnames....
select = [{'NAME'}, {'VALUE'};
{'alpha'}, 0.4;
{'sigmaL'}, 1;
{'beta'}, 0.98];
for ii = 1:size(select,1)
S.(select{ii,1}) = select{ii,2};
end
Now you have a structure S. You might get a warning because the fieldname alpha is the same as the MATLAB function ALPHA. Note that using CELL2STRUCT is preferred here, as Oleg shows...

Weitere Antworten (4)

Ben Wang
Ben Wang am 24 Apr. 2011
Thank you all for your help! It solved my problem perfectly!
Cheers
Ben

Paulo Silva
Paulo Silva am 23 Apr. 2011
select = [{'NAME'}, {'VALUE'};
{'alpha'}, 0.4;
{'sigmaL'}, 1;
{'beta'}, 0.98];
for a=2:size(select,1)
eval(sprintf('MyStruct.%s=%d',select{a,1},select{a,2}));
end
MyStruct
or
MyStruct=struct();
for a=2:size(select,1)
MyStruct=setfield(MyStruct, select{a,1}, select{a,2});
end
MyStruct

Walter Roberson
Walter Roberson am 23 Apr. 2011
struct(select{3,1}, select{3,2})
Remember, select(1,3) is the (non-existent) third column of the first row of the array select.

Oleg Komarov
Oleg Komarov am 24 Apr. 2011
cell2struct(select(2:end,2),select(2:end,1))

Kategorien

Mehr zu Structures 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