Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/matlab/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Function Matlab:使用Strg+中止函数调用;但保留返回值_Function_Matlab_Return Value_Terminate - Fatal编程技术网

Function Matlab:使用Strg+中止函数调用;但保留返回值

Function Matlab:使用Strg+中止函数调用;但保留返回值,function,matlab,return-value,terminate,Function,Matlab,Return Value,Terminate,我在matlab中有一个函数,如下所示: function [ out ] = myFunc(arg1, arg2) times = []; for i = 1:arg1 tic % do some long calculations times = [times; toc]; end % Return out = times; end 我想立即中止正在运行的函数,但保留当前已获取的时间值。怎么做?当我按

我在matlab中有一个函数,如下所示:

function [ out ] = myFunc(arg1, arg2)
    times = [];
    for i = 1:arg1
        tic
        % do some long calculations
        times = [times; toc];
    end

    % Return
    out = times;
end
我想立即中止正在运行的函数,但保留当前已获取的
时间值。怎么做?当我按下strg+c时,我只是松开它,因为它只是一个局部函数变量,当函数离开作用域时会被删除。。。

谢谢

最简单的解决方案是将其从函数转换为脚本,此时时间不再是局部变量


更优雅的解决方案是将times变量保存到循环中的.mat文件中。取决于每次迭代的时间,您可以在每个循环上执行此操作,或者每十个循环执行一次,等等。

onCleanup
函数仍然在CTRL-C存在的情况下启动,但是我认为这并没有什么帮助,因为您很难将想要的值连接到
onCleanup
函数句柄(这里有一些棘手的变量生存期问题)。使用MATLAB句柄对象跟踪值可能会更幸运。例如

x = containers.Map(); x('Value') = [];
myFcn(x); % updates x('Value') 
% CTRL-C
x('Value') % contains latest value
你不能用变量来解决你的问题吗

function [ out ] = myFunc(arg1, arg2)
    persistent times
    if nargin == 0
        out = times;
        return;
    end;
    times = [];
    for i = 1:arg1
        tic
        % do some long calculations
        times = [times; toc];
    end

    % Return
    out = times;
end

我不确定是否在Ctrl-C时清除了持久变量,但我认为不应该是这样。应该做的是:如果您提供参数,它将像以前一样运行。但是,当您忽略所有参数时,应该返回最后一个时间值。

另一个可能的解决方案是使用
assignin
函数发送在每次迭代时将数据发送到您的工作区

function [ out ] = myFunc(arg1, arg2)
    times = [];
    for i = 1:arg1
        tic
        % do some long calculations
        times = [times; toc];
        % copy the variable to the base workspace
        assignin('base', 'thelasttimes', times)
    end

    % Return
    out = times;
end

好的,谢谢。问题是:它也是从24小时开始运行的,我现在想中止它,但保留值…有办法吗?我想不出一个-对不起。还有一件事,但是-如果你键入“dbstop if error”,那么按Control-C也可以让你查看内部值。下次,我猜。啊,该死的:(但是好的,谢谢这个tipp,我会考虑到这一点,但可能只是稍微重写一下我的算法,将所有变量保存到mat文件中。