Matlab:从另一个函数终止一个函数
我有一个函数a将调用函数B,从函数B我想终止函数a。 主要问题是函数B只能在函数A不运行的情况下运行。 我知道ctr+c没有类似脚本的版本,但这不是我想要的,因为需要终止的不是函数本身,而是一个不同的函数。有办法做到这一点吗Matlab:从另一个函数终止一个函数,matlab,Matlab,我有一个函数a将调用函数B,从函数B我想终止函数a。 主要问题是函数B只能在函数A不运行的情况下运行。 我知道ctr+c没有类似脚本的版本,但这不是我想要的,因为需要终止的不是函数本身,而是一个不同的函数。有办法做到这一点吗 **function A** B(varargin) end **function B(varargin)** kill_function_A some more statements end 让我修改一下,以便更清楚: **function A** if s
**function A**
B(varargin)
end
**function B(varargin)**
kill_function_A
some more statements
end
让我修改一下,以便更清楚:
**function A**
if some_statement_is_true
B(varargin)
end
much more code
**function B(varargin)**
terminate A
update A (this is the reason why it needs to be terminated)
A (restart A, since it is now updated, I can terminate B within A if it is active)
end
请注意,A需要在B能够运行之前终止。所以“B;return”是不可能的。
(感谢所有的回答)似乎您真正想要的是在调用
B
(如果需要)之后不要执行A
中的语句。使用以下代码可以很容易地做到这一点
function A
terminate = B;
if terminate == true
return
end
end
function terminate = B
terminate = true;
end
这是否有效:
function A
if some_statement_is_true
B(varargin)
return
end
much more code
function B(varargin)
update A (this is the reason why it needs to be terminated)
A (restart A, since it is now updated, I can terminate B within A if it is active)
end
它不会“停止”A
,但实际上A
只会调用B
,这将导致或多或少相同的结果。
或者,您应该运行B
并更新某些语句是否正确:
function A
while some_statement_is_true
B(varargin);
some_statement_is_true = ...; % make sure this gets updated
end
much more code
function B(varargin)
update A;
end
编辑:
如果是独立的.exe,您可以执行以下操作来停止并运行新版本:
function A
if some_statement_is_true
B(varargin);
exit();
end
much more code
function B(varargin)
update A;
system('A.exe');
end
我已经成功地将此方案用于需要重新启动MATLAB的自更新应用程序。这是不可能的。任何退出函数A的方法都会同时退出B并返回给A的调用者。如果我可以问一下,你需要这个做什么?如果你问我…“更新A”似乎表示A有一个全局状态,所以你使用的是全局变量,对吗?你能创建一个显示你正在尝试做什么的吗?通常使用return
来终止函数,或抛出错误
,如果这不合适,那么值得后退一步,看看程序的设计。这是一个有效的解决方法,但恒定的回报不知何故是奇怪的。功能A可以简化为B;如果terminate始终为true,则返回
。@DanielR:仅举一个例子;我假设如果OP不想结束A
,他会将terminate
设置为false
。不。A真的需要终止。B需要更新脚本(即.m(或在本例中为独立的.exe)文件本身),而不仅仅是一些变量。更新文件的唯一方法是在文件未运行时进行更新。a
是来自独立的.exe文件还是.m文件会有很大的不同。对于独立的exe,您只需对现在更新的.exe和当前matlab会话发出system
调用exit()。