Matlab - AppDesigner:使用GUI中断循环

问题描述 投票:0回答:1

我创建了一个GUI,它根据外部.m文件计算轨迹。

main-gui

当用户按下“计算”按钮时,外部.m函数文件将通过按钮的回调函数调用:

% calculateBtn button pushed function
    function calculate(app)
        numSteps = app.stepSlider.Value;

        app.omega = app.omegaSpin.Value;
        app.phid = app.phi.Value;

        app.x0 = app.x0Spin.Value;
        app.y0 = app.y0Spin.Value;

        app.u0 = app.u0Spin.Value;
        app.v0 = app.v0Spin.Value;

        set(app.calculateBtn, 'Enable', 'off')
        set(app.showBtn, 'Enable', 'off')

        [app.Xc, app.Xi, app.C, T, f]=coriolis_traj(app.x0, app.y0, app.u0, app.v0, app.phid, numSteps);

        app.fEdit.Value = num2str(f);
        app.tEdit.Value = num2str(T);

        set(app.calculateBtn, 'Enable', 'on')

        if length(app.Xc)>1
            set(app.showBtn, 'Enable', 'on')
        else
            set(app.showBtn, 'Enable', 'off')
        end

    end

外部文件包含计算的主循环。

    while 1
    % Counters
    i = i + 1;
    t = t + Dt;
    theta = theta + Omega * Dt;

    % Parcel's Position 
    % on the Inertial Frame
    x1 = x0 + Dt*u0;
    y1 = y0 + Dt*v0;

    % Parcel's position translated to the
    % rotating frame
    xc1 = x1*cos(theta)+y1*sin(theta);
    yc1 = x1*sin(theta)+y1*cos(theta);

    x(i) = x1 ; y(i) = y1;
    xc(i) = xc1 ; yc(i) = yc1;

    x0 = x1 ; y0 = y1;

    [in] = inpolygon(xc,yc,xv,yv);
    if ~in(i) > 0
        break;
    end
end

当用户更改“控件”面板中的任何值或按下“按下”按钮时,我想停止计算并清除计算出的数组。

关于如何编码的任何想法?

matlab user-interface matlab-app-designer
1个回答
0
投票

我能想到的最好的解决方案是将你的while循环放入GUI回调中。你的while循环的内部代码可以保存在一个单独的外部文件中,但引入循环将使你完全控制它并使中断更容易。唯一的限制是它必须不那么“紧”......它必须包含一个小的pause(如果后跟drawnow()调用则更好),这样主GUI线程就可以有时间处理应用程序消息。

这是你的回调代码:

% Computation Callback
function Button1_Callback(obj,evd,handles)
    obj.Enable = 'off';            % disable this button
    handles.Button2.Enable = 'on'; % enable the interruption button
    handles.stop = false;          % the control variable for interruption

    while (true)
        % call your external function for running a computational cycle
        res = myExternalFunction(...);

        % refresh the application handles
        handles = guidata(obj);

        % interrupt the loop if the variable has changed
        if (handles.stop)
            break;
        end

        % this allows the loop to be interrupted
        pause(0.01);
        drawnow();
    end

    obj.Enable = 'on';
end

% Interruption Callback
function Button2_Callback(obj,evd,handles)
    obj.Enable = 'off';            % disable this button

    handles = guidata(obj);
    handles.stop = true;
end
© www.soinside.com 2019 - 2024. All rights reserved.