首先,MATLAB 不对任何图形进行多线程处理,因此您必须发挥创造力。
此外,如果您尝试在计算过程中进行一些绘图,则需要使用 drawnow 刷新回调和渲染事件。
至于知道什么时候停止,你也许可以将按钮的图形句柄传递给你的计算,它可以检查每次迭代的值?
我有一个使用persistent variable 来跟踪当前迭代并允许用户通过取消单击切换按钮来“暂停”计算的示例。
function guiThing()
figure();
hbutton = uicontrol('style', 'toggle', 'String', 'Start');
hplot = plot(NaN, NaN);
nIterations = 1000;
set(gca, 'xlim', [1 nIterations], 'ylim', [1 nIterations])
set(hbutton, 'callback', @(s,e)buttonCallback())
function buttonCallback()
% If the button is depressed, calculate the thing
if get(hbutton, 'value')
calculateThing(hbutton, hplot, nIterations);
end
end
end
% This function can live anywhere on the path!
function calculateThing(hbutton, hplot, nIterations)
% Keep track of data with persistent variables
persistent iteration
% First time to call this function, start at 1
if isempty(iteration); iteration = 1; end
for k = iteration:nIterations
iteration = k;
% If the button is not depressed then stop this
if ~get(hbutton, 'value')
return
end
% Update plotting in some way
curdata = get(hplot);
set(hplot, 'XData', [curdata.XData k], ...
'YData', [curdata.YData, k])
% Flush drawing queue
drawnow
fprintf('Iteration: %d\n', iteration);
end
end
您可以使用持久性变量来跟踪需要在迭代之间(以及停止和启动)保持的任何其他数据。