MATLAB Answers


Why does accumarray require vals and subs to be of the same size?

Asked by Jonathan on 23 Jun 2014
Latest activity Commented on by Cedric Wannaz
on 23 Jun 2014
Accepted Answer by Jan
I understand this is a built-in function and that "legacy constraints" might be the answer, but still I'm really wondering why the inputs `subs` and `vals` need to be of the same size in `accumarray`.
IMO, a sufficient input check on subs (forgetting about input cells..) would be something like
subs = floor(subs);
assert( all(subs>0) && all(subs <= numel(vals)), 'Index out ouf bounds.' );
I really don't understand this constraint, can someone explain the logic behind this?


Sign in to comment.


1 Answer

Answer by Jan
on 23 Jun 2014
 Accepted Answer

The documentation of accumarray is one of the most complicated instructions I've read. It cannot compete with the cute clarity of the other parts of Matlab's excellent docs.
The job of accumarray is "accumulating elements of the vector val using the elements of subs as indices". Therefore the number of values and the corresponding indices must be equal. The value is accumulated accoring to the subs element.


Thanks for your answer. The last part is what makes no sense to me; subs is not constrained to be a permutation of all indices (ie, may contain doublons, cf bins counting example). Hence, since subs may contain an arbitrary number of elements, there is no reason why vals should be contrained to the same size.
IMO, a typical accumulating "functional" (I mean function of function) should look like this:
function res = myaccumarray(subs,vals,fun)
if nargin<3, fun=@(a,b)(a+b); end
[u,~,v] = unique(subs);
res = zeros(1,length(u));
for i = 1:length(subs)
res(v(i)) = fun( res(v(i)), vals(subs(i)) );
My mistake sorry, I just understood your last sentence and Matlab's documentation... It's all clear now. Thanks :)
Yep, understand each element of subs as the "address" where to stack the corresponding element of vals before applying the accumulation function.

Sign in to comment.