MATLAB: Wait bar in MATLAB gui in nested FOR loop

matlab guide

I have to show a progress bar in matlab guide that appears while running FOR loop and shows progress for each iteration. Moreover, the user should not be able to close it until the calculation stops, so as to prevent the user from making any changes. Example code is as follows
MBTs = minMBT:stepMBT:maxMBT;
MATs = minMAT:stepMAT:maxMAT;
i=1;
for MAT = MATs
j = 1;
for MBT = MBTs
%some calculations
j = j + 1;
end
i = i + 1;
end

Best Answer

MBTs = minMBT:stepMBT:maxMBT;
MATs = minMAT:stepMAT:maxMAT;
n = length(MATs) * length(MBTs);
c = 0;
H = waitbar(0, 'Please wait...');
for i1 = 1:length(MATs)
MAT = MATs(i1);
for i2 = 1:length(MBTs)
MBT = MBTs(i2);
%some calculations
% Update the waitar:
if ~ishghandle(H)
error('User closed waitbar.');
end
c = c + 1;
waitbar(c / n, H, sprintf('%d of %d', c, n));
end
end
It would be brute to forbid, that the user closes the waitbar. Imagine that the loop runs for 2 hours for unknown reasons. Do you really block a premature stopping? User hate such restrictions for good reasons.