chunking.m 973 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. function varargout = chunking(varargin)
  2. % function f = chunking(v,num)
  3. %
  4. % <v> is a vector
  5. % <num> is desired length of a chunk
  6. %
  7. % return a cell vector of chunks. the last vector
  8. % may have fewer than <num> elements.
  9. %
  10. % example:
  11. % isequal(chunking(1:5,3),{1:3 4:5})
  12. %
  13. % OR
  14. %
  15. % function [f,xbegin,xend] = chunking(v,num,n)
  16. %
  17. % <v> is a vector
  18. % <num> is length of a chunk
  19. % <n> is chunk number desired
  20. %
  21. % return the desired chunk in <f>.
  22. % also return the beginning and ending indices associated with
  23. % this chunk in <xbegin> and <xend>.
  24. %
  25. % example:
  26. % isequal(chunking([4 2 3],2,2),3)
  27. switch length(varargin)
  28. case 2
  29. v = varargin{1};
  30. num = varargin{2};
  31. f = {};
  32. for p=1:ceil(length(v)/num)
  33. f{p} = v((p-1)*num+1 : min(length(v),p*num));
  34. end
  35. varargout = {f};
  36. case 3
  37. v = varargin{1};
  38. num = varargin{2};
  39. n = varargin{3};
  40. xbegin = (n-1)*num+1;
  41. xend = min(length(v),n*num);
  42. f = v(xbegin:xend);
  43. varargout = {f xbegin xend};
  44. end