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.
This is a three-fold problem.
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.