waitbar
作用:
這個函數的作用是打開或者更新進度條。
語法結構有:
(1)h = waitbar(x,'message')
(2)waitbar(x,'message','CreateCancelBtn','button_callback')
(3)waitbar(x,'message',property_name,property_value,...)
(4)waitbar(x)
(5)waitbar(x,h)
(6)waitbar(x,h,'updated message')
應用1:
語法結構h = waitbar(x,'message'); %其中x必須為0到1之間的數,message為顯示的信息,其實這個x大于1也可以啊,但是進度條總在滿的狀態,x是多少就對應進度條顯示的比例是多少
舉例:hwait=waitbar(0,'請等待>>>>>>>>'); %這個0顯示的是進度條的位置,因為是0,就在起始位置,還有就是這個hwait就是這個waitbar函數的句柄
得到:
應用2
waitbar(x,h,'updated message'); % x為顯示的進度,必須在0到1之間;h為所建立的waitbar的句柄,updated message為實時顯示的信息,常地用于for循環中。
舉例:
steps=100;
hwait=waitbar(0,'請等待>>>>>>>>');
for k=1:steps
if steps-k<=5
waitbar(k/steps,hwait,'即將完成');
pause(0.05);
else
str=['正在運行中',num2str(k),'%'];
waitbar(k/steps,hwait,str);
pause(0.05);
end;
end;
close(hwait); %注意必須添加close函數,也就是說運行完成后讓此進度條消失。
結果如下所示:
顯示正在運行中:
顯示即將完成:
應用3:
語法結構waitbar(x,'message','CreateCancelBtn','button_callback');%為的是在進度條上添加取消按鈕,用戶可以通過進度條來終止程序的運行。
舉例:
編寫函數如下;
function [valueofpi step] = approxpi(steps)
% Converge on pi in steps iterations, displaying waitbar.
% User can click Cancel or close button to exit the loop.
% Ten thousand steps yields error of about 0.001 percent.
h = waitbar(0,'1','Name','Approximating pi...',...
'CreateCancelBtn',...
'setappdata(gcbf,''canceling'',1)');
setappdata(h,'canceling',0)
% Approximate as pi^2/8 = 1 + 1/9 + 1/25 + 1/49 + ...
pisqover8 = 1;
denom = 3;
valueofpi = sqrt(8 * pisqover8);
for step = 1:steps
% Check for Cancel button press
if getappdata(h,'canceling')
break
end
% Report current estimate in the waitbar's message field
waitbar(step/steps,h,sprintf('.9f',valueofpi))
% Update the estimate
pisqover8 = pisqover8 + 1 / (denom * denom);
denom = denom + 2;
valueofpi = sqrt(8 * pisqover8);
end
delete(h)%刪除進度條,不要去使用close函數關閉。
調用函數:
[estimated_pi steps] = approxpi(10000);
運行結果: