Save workspace to unknown workspace in Matlab

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

I know that I can use the save function to save all the variable names in the workspace, but what if I want to save the workspace variables from the function that I call, for example, the built-in function (average, sum, etc.) .

I would like to save all the variables from the function workspace before returning to the function that I am writing, and I would like to do this without opening the file every time and adding an additional line of code; Is it possible?

+4
source share
2 answers

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

Using the onCleanup function , you can specify that all variables are stored immediately before the function returns to the caller. Using this and a little parsing of the files, you can open the code in question as a simple text file and paste the onCleanup code anywhere in the file (easier than pasting the save as the last line). You can then run the code and track the new .mat file using the previous file name or any naming method you choose.

, , . :

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

(filename_new.m), , (filename.mat) .

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

, .mat, , . , , .mat.

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

"". :

    save('filename')

:

    a=10; b=6;

    c=addition(a,b);

:

    function [out]=addition(a,b)
    out=a+b;
    temp1=a;
    temp2=b;
    temp3=a-b;
    save('C:\data.mat');
    end
-1

Source: https://habr.com/ru/post/1527053/


All Articles