matlabfilesave

A way to dynamically save files in Matlab?


I want to be able to save variables to disk sometimes. And I want to save it in a subfolder called '_WorkData'.

The below code works fine as a stand-alone code

OutputName = 'my favorite file';
save(['_WorkData/' OutputName '.mat'], 'foobar'); 

However as a function it can't find the variable Variable 'foobar' not found.

function noDataReturn = saveFileDisk(name,variable)
    
    save(['_WorkData/' name '.mat'], variable);
    
    noDataReturn = 'file saved';
    
end

I can see why this happens but I'm not familiar enough with Matlab code to understand how to correct it.


Solution

  • This is a three-fold problem.

    1. You have to pass the variable to your function (and not the string)
    2. However, the save call actually needs the string
    3. The function has to have a variable with the original name to save it as intended.

    Here's how it works:

    function noDataReturn = saveFileDisk(name,variable)
    
        savename = sprintf('%s',inputname(2));
    
        S.(savename) = variable;
    
        save(['_WorkData/' name '.mat'], '-struct', 'S', savename);
    
        noDataReturn = 'file saved';
    
    end
    

    You obtain the original variable name using the inputname function (in this case, the second input is what you are after).
    Next, you need to create a struct with a field name corresponding to your original variable name.
    With this, you can utilize the save function's option to save fields from a struct individually.
    Now, when you call

    saveFileDisk('test_name',foobar)
    

    the result will be a variable foobar in your test_name.mat-file.