splitmatrix.m 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. function f = splitmatrix(m,dim,splt)
  2. % function f = splitmatrix(m,dim,splt)
  3. %
  4. % <m> is a matrix
  5. % <dim> is a dimension
  6. % <splt> (optional) is a vector of positive integers indicating
  7. % how to perform the split. default: ones(1,size(m,dim)).
  8. % you can also flip the sign of entries to indicate that you
  9. % do not want that entry returned. special case is <splt>==0
  10. % which means use <splt> equal to size(m,dim).
  11. %
  12. % split <m> along dimension <dim>, returning a cell vector of matrices.
  13. %
  14. % example:
  15. % isequal(splitmatrix([1 2; 3 4],2),{[1 3]' [2 4]'})
  16. % isequal(splitmatrix([1 2 3 4],2,[2 -1 1]),{[1 2] [4]})
  17. % input
  18. if ~exist('splt','var') || isempty(splt)
  19. splt = []; % deal with later
  20. end
  21. if isequal(splt,0)
  22. splt = size(m,dim);
  23. end
  24. % what is the max number of dimensions involved?
  25. maxdim = max(ndims(m),dim); % 5
  26. % figure out the dimensions of m
  27. msize = ones(1,maxdim);
  28. msize(1:ndims(m)) = size(m); % [50 60 40 1 2]
  29. % convert to cell
  30. msize = num2cell(msize); % {50 60 40 1 2}
  31. % hack it in
  32. if isempty(splt)
  33. splt = ones(1,size(m,dim));
  34. end
  35. msize{dim} = abs(splt); % {50 60 40 1 [1 1]}
  36. % do it
  37. prev = warning('query'); warning('off');
  38. f = flatten(mat2cell(m,msize{:}));
  39. warning(prev);
  40. f = f(splt > 0);