主要内容

在后台运行函数时更新等待条

此示例说明如何使用 afterEach 按照后台运行函数的进度更新等待条。

创建一个等待条 w

w = waitbar(0,'Please wait ...');

为您的 for 循环设置迭代次数 N。将当前完成的迭代次数 0 和总迭代次数 N 存储在等待条的 UserData 属性中。

N = 20;
w.UserData = [0 N];

运行具有 N 次迭代的 for 循环。在每次迭代中,使用 parfevalbackgroundPool 在后台运行 pause,运行持续一个随机的秒数。将每个 Future 对象存储在数组中。

for i = 1:N
    delay = rand;
    f(i) = parfeval(backgroundPool,@pause,0,delay);
end

使用辅助函数 updateWaitbar 以在每个 Future 完成后更新等待条。

afterEach(f,@(~)updateWaitbar(w),0);

在所有 Future 对象完成后,使用 delete 关闭等待条。

afterAll(f,@(~)delete(w),0);

定义辅助函数

定义辅助函数 updateWaitbar。该函数递增 UserData 属性的第一个元素,然后使用该向量计算进度。

function updateWaitbar(w)
    % Update a waitbar using the UserData property.

    % Check if the waitbar is a reference to a deleted object
    if isvalid(w)
        % Increment the number of completed iterations 
        w.UserData(1) = w.UserData(1) + 1;

        % Calculate the progress
        progress = w.UserData(1) / w.UserData(2);

        % Update the waitbar
        waitbar(progress,w);
    end
end

另请参阅

|

主题