But, now it outputs a vector of vectors. I’d like instead for it to be a matrix.
Actually, I’m still very new to julia and I’ve grown pretty confused on weather I should use for loops or not; as much as I really like the broadcasting function for readability, nested for loops are also not that hard to read. My main concern is I have many functions like the above, and my simple approach has always been to not write a function and just do:
res=reshape(1:9,:,1) .+ reshape(1:9,1,:)
Having a bunch of scalar functions instead is much easier to troubleshoot, and change if required. But my functions sometimes need 3d output and do things like:
res=fill(NaN,9,9,9)
for i=1:9
res[:,:,i]= i .+ reshape(1:9,:,1) .+ reshape(1:9,1,:)
end
What’s the best way to handle things like this, I definitely want better readability, but I also really want better performance.
whichever is more clear for your use case, Julia is not a language where for-loop would be slow anyway, it doesn’t matter much as long as you try to find the way to do it such that it’s clear and minimize memory stress
Do you think there is a more compact way of writing this? I haven’t timed it but it seems like it’ll be faster than pre-allocating. Actually that’s another thing that confuses me, julia documentations said that for loops are faster than broadcasting but it said pre-allocating takes up memory. So which is faster, does preallocating and a for loop take up fewer resources than broadcasting?
So reshape(1:9, :, 1) can be replaced by just 1:9, and reshape(1:9, 1, :) by (1:9)'. For reshape(1:9, 1, 1, :) it’s not as easy, so just keep that.
Loops and broadcasting aren’t necessarily different in performance, but loops sometimes lets you avoid unnecessary allocations and do other little tricks. But here, the allocations are not unnecessary, and broadcasting is much more convenient, so just use that.
Could I generalize this statement some and say: “If pre-allocation is necessary; then broadcasting might be better. If pre-allocation is unnecessary then use a for loop.”?
You can probably find counter-examples to that, but it’s not too bad. Perhaps: if broadcasting doesn’t cause unnecessary extra allocations and makes your code clearer, then definitely use that.