0

有谁知道以下更清洁的解决方案:我正在运行一个可能需要在某个时候被杀死的 matlab 脚本。点击“cntrl-C”可以工作,但会在调试中弹出一些随机文件,并且可能仍然会失败,具体取决于图形是否在绘图中间。

我能想到的最好的方法:在我正在查看的图形上添加一个按钮,单击鼠标执行“全部清除”。简单地做“错误”是行不通的,因为它会引发一些 matlab 函数成功捕获并继续运行的异常。

更新/澄清:强制崩溃依赖于清除主脚本中的一些全局变量。

function  myScript()
global foo;
foo = 1;
while 1

x = DoStuff();
sh = figure(1);
if k == 1
  killable_window( sh );
end
x.display();
drawnow;
y = foo + 1; % <-- crashes if the callback does 'clear all', which kills global variable foo
end


end

然后这是一个可杀死窗口的脏版本:

function [] = killable_window( sh )
  S.fh = sh;
  S.pb = uicontrol('style','push',...
                 'units','pix',...
                 'position',[10 30 80 20],...
                 'fontsize',12,...
                 'string','Quit');          

set(S.pb,'callback'   ,{@pb_call,S})
% Check if 'p' is pressed when focus on button and exec callback
set(S.pb,'KeyPressFcn',{@pb_kpf ,S});

% Check if 'p' is pressed when focus on figure and exec callback
set(S.fh,'KeyPressFcn',{@pb_kpf ,S});

% Callback for pushbutton, clears all variables
function pb_call(varargin)
  S = varargin{3};  % Get the structure.

  fprintf('force quitting due to button press...\n');

  % ghetto: clear everything to force a crash later
  % and prevent anyone from successfully catching an exception
  clear all;
end

% Do same action as button when pressed 'p'
function pb_kpf(varargin)
  if varargin{1,2}.Character == 'p'
      pb_call(varargin{:})
  end
end
end

所以,如果我不喜欢我所看到的,我点击“退出”按钮,然后它转储回主屏幕,但我在这个过程中丢失了我的变量......有没有办法退出,或者“错误” “防止任何人捕获异常?

4

1 回答 1

0

也许以下内容可以帮助您在 GUIDE 应用程序中组织代码。我已使用应用程序数据(请参阅此处的appdata文档此处的一般文档)来创建执行标志runflag。一旦按下开始按钮,主循环就会在按钮的回调中进入。当按下停止按钮设置将图形应用程序数据中的标志设置为 FALSE 时,循环终止。

这是我用来设置它的步骤。

  1. 首先创建一个新的 GUIDE 应用程序,
  2. 添加两个按钮(开始和停止)和
  3. 定义以下回调

打开函数回调

%# --- Executes just before testStop is made visible.
function testStop_OpeningFcn(hObject, eventdata, handles, varargin)

%# Choose default command line output 
handles.output = hObject;

%# Add a global variable as a MATLAB application data 
%# see sharing application data  documentation in the MATLAB
%# docs 
%# APPDATA documentation:
%#    http://www.mathworks.com/help/techdoc/creating_guis/f13-998352.html#f13-999565
%# General doc on sharing application data
%#    http://www.mathworks.com/help/techdoc/creating_guis/f13-998449.html
%# 
setappdata(handles.figure1,'runFlag',true);

%# Update handles structure
guidata(hObject, handles);

开始按钮回调

%# --- Executes on button press in btnGo.
function btnGo_Callback(hObject, eventdata, handles)
i=0;

%# This loop will stop when the stop button is pressed
%# setting the application data _runFlag_ to false
while  getappdata(handles.figure1,'runFlag')
    i=i+1;
    %# Work you want to inturrupt can go here.
    pause(.1)
end

停止按钮回调

%# --- Executes on button press in btnStop.
function btnStop_Callback(hObject, eventdata, handles)            
setappdata(handles.figure1,'runFlag',false)
于 2011-03-03T20:12:46.233 回答