chunkfun.m 806 B

1234567891011121314151617181920212223242526
  1. function f = chunkfun(v,nums,fun)
  2. % function f = chunkfun(v,nums,fun)
  3. %
  4. % <v> is a row or column vector
  5. % <nums> is a vector of counts such that sum(<nums>) is equal to length(<v>)
  6. % <fun> (optional) is a function that takes A x B to 1 x B. each column consists
  7. % of a mix of valid elements (comprising a group in <v>) and NaNs. <fun>
  8. % should compute something based on the valid elements in each column.
  9. % default: @(y)nansum(y,1).
  10. %
  11. % return a row vector by applying <fun> to <v> reshaped into groups.
  12. % we emphasize fast execution!
  13. %
  14. % example:
  15. % isequal(chunkfun([1 2 3 5 6],[3 2]),[6 11])
  16. % input
  17. if ~exist('fun','var') || isempty(fun)
  18. fun = @(y)nansum(y,1);
  19. end
  20. % do it
  21. f = NaN(max(nums),length(nums));
  22. f(bsxfun(@le,repmat((1:max(nums))',[1 length(nums)]),nums)) = v;
  23. f = feval(fun,f);