如果我调用的函数不能进行显式编辑而需要进行文件I/O,那么是否有可能保存工作区变量?
我知道可以使用save函数保存工作区中的所有变量名,但是如果我想要保存从我所调用的函数(如mean、sum等内置函数)中的工作区变量呢?
在它返回到我编写的函数之前,我希望保存从函数的工作区中获取的所有变量,并且我希望不需要每次打开文件并添加额外的代码行。这种情况是否可能实现?
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
eval(newFileName(1:end-2));
matObj = matfile('filename.mat');
stats = whos(matObj);
fileSize = sum([stats.bytes]);
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