493: Undecipherable

-Blog-

-Projects-

-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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
function doArrayFunWithProgressBar()
  data = magic(35);
  WAITBAR = waitbar(0, 'Work in progress');
  PROGRESS_COUNTER = 0;
  PROGRESS_MAX = sum(size(data));

  data = arrayfun(@(item)innerFun(item), data);

  close(WAITBAR);

  function result= innerFun(item) 
    %TODO Do the work!
    pause(1);

    PROGRESS_COUNTER = PROGRESS_COUNTER + 1;
    waitbar(PROGRESS_COUNTER / PROGRESS_MAX);
  end
end