Search code examples
matlaboptimizationsavecell-arraymat-file

Save multiple variables from a list of names in one go without using loop


I'm trying to save list of variables from the workspace into a .mat file. The problem I encountered is that I'm trying to make a function of it, and that function should be able to handle a list of variables to be saved. I could loop as below:

vars = {'a','b','c'}; % names of variables
for k = 1:numel(vars)
    save(filename,vars(k),'-append');
end

but this is not elegant for me and the flag -append slowed down the process. I'm trying to achieve something like this:

vars = {'a','b','c'}; %names of variables
save(filename,vars);

Is this possible?


Solution

  • Since save expects each variable name as a separate input argument, you can use a comma-separated list generated from the cell array:

    save(filename, vars{:})