dynamic variable declaration

喜你入骨 提交于 2019-12-13 06:20:42

问题


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


来源:https://stackoverflow.com/questions/21831692/dynamic-variable-declaration

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!