Search code examples
matlabworkspace

How to save function variable to file in MATLAB


I want to make a script that saves multiple base variables from the "base name". My attempt looks like this :

function [outargs] = save_with_basename(b)

basePath = 'C:\path\';

Var1 = evalin('base', [b '_1']);
Var2 = evalin('base', [b '_2']); % .. etc

for i=1:N
    save([basePath b '_' int2str(i) '.mat'], ['Var' int2str(i)]);
end

end

This saves the files but the variable saved in the file is called Var1 (see the pic.), but I want it to be called 'Foo_1' if the function was called with :

save_with_basename('Foo');

I think the second argument to save works with the function variable, so it looks like I have to change its name dynamically (which is probably not possible?) , so I wonder if there is a way I can do it.

Here is the problem : enter image description here

Thanks for any help !


Solution

  • For the sake of everything that is holy, please do not do this.

    If you really have to, please please please do not do this.

    If you really really really have to want to, you indeed need to use dynamic variables (but that doesn't make much of a difference now, does it?):

    for i=1:N %what's N again?
       evalin('base',['Var' num2str(i) '=' b '_' num2str(i)]);
       evalin('base',['save([''' basePath b '_' num2str(i) '.mat''], [''Var' num2str(i) '''])']);
    end
    

    This will essentially perform

    Var1 = "b"_1; %with whatever b is
    Var2 = "b"_2;
    ...
    save(['C:\path\b_1.mat'],['Var1']); %with whatever b is
    save(['C:\path\b_2.mat'],['Var2']);
    

    in your base workspace, so it will generate the Var* variables there. Small price to pay for selling your soul to the devil. Note that I may have missed the escaping of the single quotes in the second evalin.