dynamic variable declaration

2019-09-17 20:40发布

问题:

Suppose we have loaded data into cell array:

DATA={'foo',[1,5];'bar',[2,6]}

Is there way how to declare variables named by 1st column in DATA with content of 2nd column?

回答1:

You can do that using eval

for ii = 1:size(DATA,1)
    eval( [DATA{ii,1}, ' = ', num2str( DATA{ii,2} )] );
end

However, use of eval is not recommended.

You can use dynamic field names instead:

s = cell2struct( DATA(:,2), DATA(:,1), 2 );


回答2:

There's an assignin function which takes a variable name and assign to it a specific value:

for r = 1:size (DATA, 1)
  assignin ('caller', DATA{r,:});
end