Get waitbar value in Matlab

2019-08-04 12:30发布

问题:

How could I get the value of a waitbar in Matlab? That is, to know if 50% filled, 75%, and so on. I guess it could be done using the handle (h) returned when the progress bar is created:

> h = waitbar(0,'Please Wait');

I guess this is a pretty simple question, however, I have been trying for I while without solving it. Thanks

回答1:

There are two methods.

First, from the documentation for waitbar():

waitbar(x) subsequent callsto waitbar(x) extend the length of the bar to thenew position x. Successive values of x normallyincrease. If they decrease, the wait bar runs in reverse.

waitbar(x,h) extends thelength of the bar in the wait bar h to the newposition x.

waitbar(x,h,'updated message') updates the message text in the waitbar figure,in addition to setting the fractional length to x.

Where x is a value between 0 and 1.

Second, and more general:

get() and set() will allow you to obtain and change MATLAB object properties. Executing get(h) will return a list of all the documented properties of object handle h you can address and modify.

For GUIs where you don't have a complete knowledge of the object handle structure it may not be readily apparent which object's property you need to adjust in order to achieve the results you want. In the case of waitbar(), it appears from my quick poking around that you need to go down a few child layers to get to the plotted bar portion that you can modify with set(). This seems like far more effort than it's worth given that the functionality of waitbar() is sufficient.

As far as finding out what the value is from a preexisting waitbar, which is a pretty roundabout way to go about it (why not just look at the code that's generating it?):

h = waitbar(0,'Please Wait');
level1 = get(h,'Children');
level2 = get(level1,'Children');
test = get(level2(2),'xdata');

Returns:

test = [0 0 0 0]

Executing:

waitbar(0.5,h)   
test = get(level2(2),'xdata');

Returns:

test = [0 50 50 0]

Which I don't believe is the correct field to modify to update the bar (modifying it and forcing an update with drawnow doesn't seem to have an affect), but it answers the question.



回答2:

If you just want to know how much percentage you have progressed in numbers do the following. This will display percentage in waitbar itself.

a = randi(3,1,4000);

h = waitbar(0,'iteration');

for i = 1:3999

    x(i) = a(i)*a(i+1);

    waitbar(i/3999,h,sprintf('percentage = %2.2f',i/40))

end

close(h)

You may print any loop value inside sprintf() so you can at any point see the current value there. Obviously content of loop must be complicated ,otherwise you may not get time to read.