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?
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 );
num2str instead of my personal favorite sprintf just to cover simple vectors. But eval has indeed limitations here. Maybe combined with disp? I prefer struct with dynamic names...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
'base' instead of in the context of the function :Obase and caller, I thought caller was 1 level down in the stack, and base the current scope.