Friday, February 4, 2011

Matlab: Progressbar for arrayfun

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:
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