493: Undecipherable

-Blog-

-Projects-

-Urlaub-

-About me-

-RSS-

Matlab: Progressbar for arrayfun

Dennis Guse

If you use arrayfun on large arrays with really slow functions it is annoying to wait without feedback how long it can take - so a progressbar (in matlab waitbar) would be nice. One problem is that arrayfun provides no information about the status - there are no callback handlers. What could be done instead. Simply write function for arrayfun as inner function of the function which calls arrayfun. In the calling function you define two variables, one for the number of items and one for the current solved items (starts with 0 and gets updated). In the inner function the work is done and the counter increment, which is visible in the inner function, because it is an inner function. At last update the waitbar. Here is how it can look:

 1 function doArrayFunWithProgressBar()
 2   data = magic(35);
 3   WAITBAR = waitbar(0, 'Work in progress');
 4   PROGRESS_COUNTER = 0;
 5   PROGRESS_MAX = sum(size(data));
 6 
 7   data = arrayfun(@(item)innerFun(item), data);
 8 
 9   close(WAITBAR);
10 
11   function result= innerFun(item) 
12     %TODO Do the work!
13     pause(1);
14 
15     PROGRESS_COUNTER = PROGRESS_COUNTER + 1;
16     waitbar(PROGRESS_COUNTER / PROGRESS_MAX);
17   end
18 end