Equivalent to MATLAB/Octave accumarray()

316 views
Skip to first unread message

Júlio Hoffimann

unread,
Jun 3, 2015, 1:06:33 AM6/3/15
to julia...@googlegroups.com
Hi,

Is there any equivalent to accumarray() in Julia? http://www.mathworks.com/help/matlab/ref/accumarray.html

-Júlio

Isaiah Norton

unread,
Jun 3, 2015, 9:11:38 AM6/3/15
to julia...@googlegroups.com

Júlio Hoffimann

unread,
Jun 3, 2015, 9:20:20 AM6/3/15
to julia...@googlegroups.com

Thank you Isaiah, is there a reason to not add it to Base?

-Júlio

Tim Holy

unread,
Jun 3, 2015, 10:20:49 AM6/3/15
to julia...@googlegroups.com
On Wednesday, June 03, 2015 06:20:17 AM Júlio Hoffimann wrote:
> Thank you Isaiah, is there a reason to not add it to Base?

I suppose we could add it, but rather than write a clone of Matlab's 6-
argument function (hmm, I want a sparse matrix output, is `issparse` the 5th
or 6th argument to `accumarray`?), the flexibility of writing your own loops is
pretty hard to beat. I mean, the basic return-an-array version

function accumarray(subs, val, sz=(maximum(subs),))
A = zeros(eltype(val), sz...)
for i = 1:length(val)
A[subs[i]] += val[i]
end
A
end

is dirt simple, and probably about as fast to write as it is to look up the
documentation for Matlab's version.

Other problems:
- having an `issparse` input makes the result not be type-stable (though there
are ways around this)
- a Dict output will almost always be preferable to a sparse-matrix output, if
that's what you want, and is scarcely any more lines of code
- why would you even want to construct the inputs, subs and val, explicitly?
Why not just do it on-the-fly in the middle of your computation? That will
always be faster, more memory efficient, etc.

In the end, the only reason you need something like accumarray in Matlab is
because you can't write fast loops. In Julia, you can. That doesn't mean we
can't have accumarray, but if it's added it should be given a decent interface
(and therefore be different from the Matlab version).

--Tim

Júlio Hoffimann

unread,
Jun 3, 2015, 10:23:23 AM6/3/15
to julia...@googlegroups.com

Totally agree Tim, thank you for sharing your thoughts on that.

-Júlio

Reply all
Reply to author
Forward
0 new messages