确定最近评估的变量并将其保存到.mat-file

时间:2015-04-08 20:31:08

标签: matlab

有没有办法在Matlab中找到最近评估的变量? whowhos似乎没有在工作区中为变量添加时间戳。

这是一个用例。我想有一个泛型函数'probe()',可以在Matlab脚本/代码中的任何地方调用。我想将最近评估的变量保存到.mat文件,而不必传递与保存的变量相关的任何自定义参数。这可能吗?

ans接近我想要实现的目标,但由于我的代码在分配中的左侧上有变量,因此无法使用。

2 个答案:

答案 0 :(得分:1)

如果您在命令提示符中执行此操作,那么您可以执行use this post by gnovice来检索整个命令历史记录,因为您已将MATLAB打开到文本数组。一旦你这样做,你只需在等号前面的倒数第二个行搜索变量....假设你做了一个lhs语句。您还需要考虑到您在命令提示符中回显变量而没有左侧语句。我们可以通过regexp轻松找到这一点。

您需要搜索文本数组的倒数第二行,因为gnovice用于捕获历史记录的代码需要额外的代码行。此代码会在历史记录中捕获,而这不是您想要的。因此,您需要查看倒数第二行/条目。

因此,请执行此操作:

history = com.mathworks.mlservices.MLCommandHistoryServices.getSessionHistory; %// From gnovice's post
historyText = char(history);

lne = historyText(end-1,:); %// Get second last line

%// Do a regexp and retrieve the text with or without the equals sign
var = regexp(lne, '\w*', 'match');

%// Get first match which is the variable before any symbols or just the word
var = var{1};

这是一个简单的例子。在尝试上述代码之前,这是我完整的命令历史记录:

>> A = rand(10,10);
>> B = A + 2;
>> D = B * 3;

运行上面的代码后,我得到了var

var = 

D

同样,如果我们只评估答案而不向左侧分配任何内容:

>> A = rand(10,10);
>> B = A + 3;
>> A

运行上面的代码,我得到:

var = 

A

要最终结束这一切,如果要将此变量保存到磁盘,可以使用eval语句来实现此目的:

>> name_of_file = 'file.mat';
>> eval(['save ' name_of_file ' ' var]);

上面的代码将采用您指定的文件名...所以在这种情况下它将是test.mat,然后使用var作为变量从工作区调用save命令喜欢保存。

答案 1 :(得分:1)

这是一个基本的草图,您可以使用函数dbstack

来完成它
function probe

%// get filename of caller file and line where probe was called
lineANDfile = dbstack;
file = lineANDfile(end).file;
linenum = lineANDfile(end).line;

%// read caller m-file
mLines = textread(file, '%s','delimiter', '\n');

%// get line previous of the line where probe was called
mLinesUntilProbeCall = mLines(1:linenum - 1);

%// last non empty line before probe call -> line of interest
mLine = mLines{ find( ~cellfun(@isempty,mLinesUntilProbeCall),1,'last') };

%// get string (variable name) left of =
varnameCell = textscan(mLine,'%s');

%// isolate varnames
getFouts = regexp(varnameCell{1}{1},'(?<=\[).+?(?=\])','match');
if isempty(getFouts)
    varnames = varnameCell{1}(1);
else
    varnames = strsplit( getFouts{1},',');
end

%// create struct with varnames as fields
for ii= 1:numel(varnames)
    probeOut.(varnames{ii}) = evalin('base',varnames{ii});
end

save('probeOut.mat','probeOut');

end

您可以在以下脚本中调用:

y = 5;
xz = 42;


probe  %// empty lines before call allowed!

它会创建一个 .mat 文件,其中包含结构probeOut和字段xz

enter image description here

再次加载 .mat 文件后:

>> probeOut.xz

ans =

    42

如果您有多个输出参数,它也会起作用:

y = 5;
[xz,z] = deal(42,5);

probe

您的 .mat -file将如下所示:

enter image description here


案例

y = 5;
[xz] = deal(42,5);

probe

也包括在内。

相关问题