Question

Is it possible to save workspace variables from a function that I am calling and cannot explicitly edit without file I/O?

I know I can use the save function to save all of the variable names in a workspace, but what if I wanted to save the workspace variables from a function that I am calling, like a built in function (mean, sum, etc).

I would like to save all of the variables from a function's workspace before it returns back to the function I am writing, and I would like to do it without opening the file each time and adding an extra line of code; is this possible?

Was it helpful?

Solution

In case anyone is interested: I have yet to find a solution to the exact question I asked, but I found a solution that works well enough with a little extra file tracking.

Using the function onCleanup, you can specify that all the variables be saved right before the function returns to the caller. Using this and a little file parsing, you can open the code in question as a simple text file, and insert the onCleanup code anywhere in the file (easier than inserting save as the last line). Then, you can run the code and track the new .mat file using the previous file name or any naming method you choose.

That will enable you to save all the variables in a workspace just before the function exits, but it does require file parsing, see simple example below:

readFile = fopen('filename.m');
writeFile = fopen(['filename_new.m']);
%Ignore the first line (hopefully the function header, may need extra parsing if not)
functionHeader = fgets(readFile);
%Print the function header
fprintf(writeFile,functionHeader);
%Print the clean-up code
%NOTE: This can go anywhere in the file
fprintf(writeFile,sprintf('onCleanup(@()save(''%s.mat''))\n',filename)));
nextLine = fgets(readFile);
while ischar(nextLine)
    fprintf(writeFile,nextLine);
    nextLine = fgets(readFile);
end

With the above, a new file is created (filename_new.m) which needs to be run, and will create a mat file (filename.mat) with all of the workspace variables in it.

eval(newFileName(1:end-2));

Now, by tracking the .mat file, you can do whatever is necessary after this point. For my purposes, I was interested in the memory used by the said function, which is available by accessing the mat object of the .mat file.

matObj = matfile('filename.mat');
stats = whos(matObj); 
fileSize = sum([stats.bytes]);

OTHER TIPS

Try the "save" function. Add this line in your called function:

    save('filename')

Here is my sample code:

    a=10; b=6;

    c=addition(a,b);

And the function is defined as:

    function [out]=addition(a,b)
    out=a+b;
    temp1=a;
    temp2=b;
    temp3=a-b;
    save('C:\data.mat');
    end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top