function f = splitmatrix(m,dim,splt) <m> is a matrix <dim> is a dimension <splt> (optional) is a vector of positive integers indicating how to perform the split. default: ones(1,size(m,dim)). you can also flip the sign of entries to indicate that you do not want that entry returned. special case is <splt>==0 which means use <splt> equal to size(m,dim). split <m> along dimension <dim>, returning a cell vector of matrices. example: isequal(splitmatrix([1 2; 3 4],2),{[1 3]' [2 4]'}) isequal(splitmatrix([1 2 3 4],2,[2 -1 1]),{[1 2] [4]})
0001 function f = splitmatrix(m,dim,splt) 0002 0003 % function f = splitmatrix(m,dim,splt) 0004 % 0005 % <m> is a matrix 0006 % <dim> is a dimension 0007 % <splt> (optional) is a vector of positive integers indicating 0008 % how to perform the split. default: ones(1,size(m,dim)). 0009 % you can also flip the sign of entries to indicate that you 0010 % do not want that entry returned. special case is <splt>==0 0011 % which means use <splt> equal to size(m,dim). 0012 % 0013 % split <m> along dimension <dim>, returning a cell vector of matrices. 0014 % 0015 % example: 0016 % isequal(splitmatrix([1 2; 3 4],2),{[1 3]' [2 4]'}) 0017 % isequal(splitmatrix([1 2 3 4],2,[2 -1 1]),{[1 2] [4]}) 0018 0019 % input 0020 if ~exist('splt','var') || isempty(splt) 0021 splt = []; % deal with later 0022 end 0023 if isequal(splt,0) 0024 splt = size(m,dim); 0025 end 0026 0027 % what is the max number of dimensions involved? 0028 maxdim = max(ndims(m),dim); % 5 0029 0030 % figure out the dimensions of m 0031 msize = ones(1,maxdim); 0032 msize(1:ndims(m)) = size(m); % [50 60 40 1 2] 0033 0034 % convert to cell 0035 msize = num2cell(msize); % {50 60 40 1 2} 0036 0037 % hack it in 0038 if isempty(splt) 0039 splt = ones(1,size(m,dim)); 0040 end 0041 msize{dim} = abs(splt); % {50 60 40 1 [1 1]} 0042 0043 % do it 0044 prev = warning('query'); warning('off'); 0045 f = flatten(mat2cell(m,msize{:})); 0046 warning(prev); 0047 f = f(splt > 0);