`broadcast` with iterators?

Start with x = randn(6, 4).

This works:

broadcast((x,tup) -> x * tup[1] * tup[2], x, collect(Base.product(0:5, 0:3)))

But of course I’d like to do this without that collect (and, eventually, in-place, overwriting x) but this doesn’t work:

broadcast((x,tup) -> x * tup[1] * tup[2], x, Base.product(0:5,0:3))

A friend tells me this is because iterators don’t know their own length, which makes sense since the error message involves not finding getindex. Is there any way to make this computation fast without for loops?

You can just use map instead of broadcast.

But in this case you could also just do broadcast(*, x, 0:5, (0:3).') or x .* (0:5) .* (0:3).' or @. x * (0:5) * (0:3).'.

2 Likes

Thanks!

But I can’t do map!((x,tup) -> x * tup[1] * tup[2], x, x, Base.product(0:5,0:3)) to overwrite x because map! can’t handle iterators, is that correct?

Apparently not, though it seems like this would be a reasonable enhancement to work on.

Honestly, though, I think you’ve passed the point where it is easier and clearer just to write a loop.

2 Likes