1## Copyright (C) 2007, 2008, 2009 David Bateman
2## Copyright (C) 2009, 2010 VZLU Prague
4## This file is part of Octave.
6## Octave is free software; you can redistribute it and/or modify it
7## under the terms of the GNU General Public License as published by
8## the Free Software Foundation; either version 3 of the License, or (at
9## your option) any later version.
11## Octave is distributed in the hope that it will be useful, but
12## WITHOUT ANY WARRANTY; without even the implied warranty of
13## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14## General Public License for more details.
16## You should have received a copy of the GNU General Public License
17## along with Octave; see the file COPYING. If not, see
18## <http://www.gnu.org/licenses/>.
21## @deftypefn {Function File} {} accumarray (@var{subs}, @var{vals}, @var{sz}, @var{func}, @var{fillval}, @var{issparse})
22## @deftypefnx {Function File} {} accumarray (@var{csubs}, @var{vals}, @dots{})
24## Create an array by accumulating the elements of a vector into the
25## positions defined by their subscripts. The subscripts are defined by
26## the rows of the matrix @var{subs} and the values by @var{vals}. Each row
27## of @var{subs} corresponds to one of the values in @var{vals}.
29## The size of the matrix will be determined by the subscripts themselves.
30## However, if @var{sz} is defined it determines the matrix size. The length
31## of @var{sz} must correspond to the number of columns in @var{subs}.
33## The default action of @code{accumarray} is to sum the elements with the
34## same subscripts. This behavior can be modified by defining the @var{func}
35## function. This should be a function or function handle that accepts a
36## column vector and returns a scalar. The result of the function should not
37## depend on the order of the subscripts.
39## The elements of the returned array that have no subscripts associated with
40## them are set to zero. Defining @var{fillval} to some other value allows
41## these values to be defined.
43## By default @code{accumarray} returns a full matrix. If @var{issparse} is
44## logically true, then a sparse matrix is returned instead.
46## An example of the use of @code{accumarray} is:
50## accumarray ([1,1,1;2,1,2;2,3,2;2,1,2;2,3,2], 101:105)
51## @result{} ans(:,:,1) = [101, 0, 0; 0, 0, 0]
52## ans(:,:,2) = [0, 0, 0; 206, 0, 208]
56## The complexity in the non-sparse case is generally O(M+N), where N is the number of
57## subscripts and M is the maximum subscript (linearized in multidimensional case).
58## If @var{func} is one of @code{@@sum} (default), @code{@@max}, @code{@@min}
59## or @code{@@(x) @{x@}}, an optimized code path is used.
60## Note that for general reduction function the interpreter overhead can play a
61## major part and it may be more efficient to do multiple accumarray calls and
62## compute the results in a vectorized manner.
65function A = accumarray (subs, val, sz = [], func = [], fillval = [], isspar = [])
67 if (nargin < 2 || nargin > 6)
72 subs = cellfun (@(x) x(:), subs, "UniformOutput", false);
78 ndims = columns (subs);
81 if (isempty (fillval))
91 ## Sparse case. Avoid linearizing the subscripts, because it could overflow.
94 error ("accumarray: fillval must be zero in the sparse case");
97 ## Ensure subscripts are a two-column matrix.
102 ## Validate dimensions.
106 error ("accumarray: in the sparse case, needs 1 or 2 subscripts");
109 if (isnumeric (val) || islogical (val))
112 error ("accumarray: in the sparse case, values must be numeric or logical");
115 if (! (isempty (func) || func == @sum))
117 ## Reduce values. This is not needed if we're about to sum them, because
118 ## "sparse" can do that.
121 [subs, idx] = sortrows (subs);
124 jdx = find (any (diff (subs, 1, 1), 2));
127 val = cellfun (func, mat2cell (val(:)(idx), diff ([0; jdx])));
134 ## Form the sparse matrix.
136 A = sparse (subs(:,1), subs(:,2), val, mode);
137 elseif (length (sz) == 2)
138 A = sparse (subs(:,1), subs(:,2), val, sz(1), sz(2), mode);
140 error ("accumarray: dimensions mismatch")
145 ## Linearize subscripts.
149 sz = cellfun (@max, subs);
151 sz = max (subs, [], 1);
153 elseif (ndims != length (sz))
154 error ("accumarray: dimensions mismatch")
157 ## Convert multidimensional subscripts.
159 subs = num2cell (subs, 1);
161 subs = sub2ind (sz, subs{:}); # creates index cache
162 elseif (! isempty (sz) && length (sz) < 2)
163 error ("accumarray: needs at least 2 dimensions");
164 elseif (! isindex (subs)) # creates index cache
165 error ("accumarray: indices must be positive integers");
169 ## Some built-in reductions handled efficiently.
171 if (isempty (func) || func == @sum)
174 A = __accumarray_sum__ (subs, val);
176 A = __accumarray_sum__ (subs, val, prod (sz));
181 ## we fill in nonzero fill value.
183 mask = true (size (A));
187 elseif (func == @max)
188 ## Fast maximization.
191 zero = intmin (class (val));
192 elseif (islogical (val))
194 elseif (fillval == 0 && all (val(:) >= 0))
195 ## This is a common case - fillval is zero, all numbers nonegative.
198 zero = NaN; # Neutral value.
202 A = __accumarray_max__ (subs, val, zero);
204 A = __accumarray_max__ (subs, val, zero, prod (sz));
208 if (fillval != zero && isnan (fillval) != isnan (zero))
209 mask = true (size (A));
213 elseif (func == @min)
214 ## Fast minimization.
217 zero = intmax (class (val));
218 elseif (islogical (val))
221 zero = NaN; # Neutral value.
225 A = __accumarray_min__ (subs, val, zero);
227 A = __accumarray_min__ (subs, val, zero, prod (sz));
231 if (fillval != zero && isnan (fillval) != isnan (zero))
232 mask = true (size (A));
238 ## The general case. Reduce values.
240 if (numel (val) == 1)
241 val = val(ones (1, n), 1);
247 [subs, idx] = sort (subs);
249 jdx = find (subs(1:n-1) != subs(2:n));
251 val = mat2cell (val(idx), diff ([0; jdx]));
252 ## Optimize the case when function is @(x) {x}, i.e. we just want to
253 ## collect the values to cells.
254 persistent simple_cell_str = func2str (@(x) {x});
255 if (! strcmp (func2str (func), simple_cell_str))
256 val = cellfun (func, val);
260 ## Construct matrix of fillvals.
263 elseif (fillval == 0)
264 A = zeros (sz, class (val));
266 A = repmat (fillval, sz);
269 ## Set the reduced values.
275%!error (accumarray (1:5))
276%!error (accumarray ([1,2,3],1:2))
277%!assert (accumarray ([1;2;4;2;4],101:105), [101;206;0;208])
278%!assert (accumarray ([1,1,1;2,1,2;2,3,2;2,1,2;2,3,2],101:105),cat(3, [101,0,0;0,0,0],[0,0,0;206,0,208]))
279%!assert (accumarray ([1,1,1;2,1,2;2,3,2;2,1,2;2,3,2],101:105,[],@(x)sin(sum(x))),sin(cat(3, [101,0,0;0,0,0],[0,0,0;206,0,208])))
280%!assert (accumarray ({[1 3 3 2 3 1 2 2 3 3 1 2],[3 4 2 1 4 3 4 2 2 4 3 4],[1 1 2 2 1 1 2 1 1 1 2 2]},101:112),cat(3,[0,0,207,0;0,108,0,0;0,109,0,317],[0,0,111,0;104,0,0,219;0,103,0,0]))
281%!assert (accumarray ([1,1;2,1;2,3;2,1;2,3],101:105,[2,4],@max,NaN),[101,NaN,NaN,NaN;104,NaN,105,NaN])
282%!assert (accumarray ([1 1; 2 1; 2 3; 2 1; 2 3],101:105,[2 4],@prod,0,true),sparse([1,2,2],[1,1,3],[101,10608,10815],2,4))
283%!assert (accumarray ([1 1; 2 1; 2 3; 2 1; 2 3],1,[2,4]), [1,0,0,0;2,0,2,0])
284%!assert (accumarray ([1 1; 2 1; 2 3; 2 1; 2 3],101:105,[2,4],@(x)length(x)>1),[false,false,false,false;true,false,true,false])
286%! A = accumarray ([1 1; 2 1; 2 3; 2 1; 2 3],101:105,[2,4],@(x){x});
287%! assert (A{2},[102;104])
289%! subs = ceil (rand (2000, 3)*10);
290%! val = rand (2000, 1);
291%! assert (accumarray (subs, val, [], @max), accumarray (subs, val, [], @(x) max (x)));
293%! subs = ceil (rand (2000, 1)*100);
294%! val = rand (2000, 1);
295%! assert (accumarray (subs, val, [100, 1], @min, NaN), accumarray (subs, val, [100, 1], @(x) min (x), NaN));
297%! subs = ceil (rand (2000, 2)*30);
298%! subsc = num2cell (subs, 1);
299%! val = rand (2000, 1);
300%! assert (accumarray (subsc, val, [], [], 0, true), accumarray (subs, val, [], [], 0, true));
302%! subs = ceil (rand (2000, 3)*10);
303%! subsc = num2cell (subs, 1);
304%! val = rand (2000, 1);
305%! assert (accumarray (subsc, val, [], @max), accumarray (subs, val, [], @max));