function f = chunkfun(v,nums,fun) <v> is a row or column vector <nums> is a vector of counts such that sum(<nums>) is equal to length(<v>) <fun> (optional) is a function that takes A x B to 1 x B. each column consists of a mix of valid elements (comprising a group in <v>) and NaNs. <fun> should compute something based on the valid elements in each column. default: @(y)nansum(y,1). return a row vector by applying <fun> to <v> reshaped into groups. we emphasize fast execution! example: isequal(chunkfun([1 2 3 5 6],[3 2]),[6 11])
0001 function f = chunkfun(v,nums,fun) 0002 0003 % function f = chunkfun(v,nums,fun) 0004 % 0005 % <v> is a row or column vector 0006 % <nums> is a vector of counts such that sum(<nums>) is equal to length(<v>) 0007 % <fun> (optional) is a function that takes A x B to 1 x B. each column consists 0008 % of a mix of valid elements (comprising a group in <v>) and NaNs. <fun> 0009 % should compute something based on the valid elements in each column. 0010 % default: @(y)nansum(y,1). 0011 % 0012 % return a row vector by applying <fun> to <v> reshaped into groups. 0013 % we emphasize fast execution! 0014 % 0015 % example: 0016 % isequal(chunkfun([1 2 3 5 6],[3 2]),[6 11]) 0017 0018 % input 0019 if ~exist('fun','var') || isempty(fun) 0020 fun = @(y)nansum(y,1); 0021 end 0022 0023 % do it 0024 f = NaN(max(nums),length(nums)); 0025 f(bsxfun(@le,repmat((1:max(nums))',[1 length(nums)]),nums)) = v; 0026 f = feval(fun,f);