Gregor Isack
Gregor Isack

Reputation: 1141

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?

Upvotes: 3

Views: 1273

Answers (1)

Luis Mendo
Luis Mendo

Reputation: 112759

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{:})

Upvotes: 3

Related Questions