Reputation: 2570
Is it possible to declare global variables in MATLAB inside a loop:
cellvar = { 'ni' ; 'equity' ; 'assets' } ;
for i = 1:size(cellvar,1)
global cellvar{1} % --> THIS GIVES AN ERROR
end
% Desired result:
global ni
global equity
global assets
Matlab documentation says: "There is no function form of the global command (i.e., you cannot use parentheses and quote the variable names)." Any suggested work-around? Thanks!
Upvotes: 3
Views: 1800
Reputation: 125874
You can use the EVAL function to do this:
for var = 1:numel(cellvar)
eval(['global ' cellvar{var}]);
end
Also, since GLOBAL accepts a command-line list of variable names, you could avoid the for loop by using SPRINTF to concatenate your variable names into one string to be evaluated:
eval(['global' sprintf(' %s',cellvar{:})]);
Upvotes: 6