Search code examples
matlabscopesaveworkspace

Using matlabs save in functions


Is it possible to use the Matlab save command inside a function to store workspace variables?

Consider following scenario: I've got a bunch of variables in the Matlab workspace and want all that are beginning with "a" and "b" in a .mat file. Of course this works:

save('test.mat','a*','b*')

but i want to have a variable filename. The function i wrote:

function save_with_name(name)
save(name,'a*','b*')

does not work, because save_with_name doesn't see the workspace variables. Is there a solution which i can use?


Solution

  • You need to evaluate save in the base workspace.

    function save_with_name(name)
    expression = ['save(''', name, ''',''a*'',''b*'')'];
    evalin('base',expression);
    

    The double-quotes ('') in the expression are necessary to allow the quote character itself ('). Thus the command you're looking for is: evalin