Where the summation excludes identical indices. In Julia, the only way I know how to do this is with nested loops and an if statement, eg:
x = [1 2 3 4 5]
y = zeros(5)
for i in eachindex(x), j in eachindex(x)
if i != j
y[i] += 1/(x[i] - x[j])
end
end
This is functional, but rather clunky to write. Is there a more concise/elegant/idiomatic way to write “hey, sum/multiply these terms over all indices, but exclude this special case”? (Note: the function above is a good example of where you might encounter this excluded index summation, since it avoids a divide-by-zero error, but that’s hardly the only application.)
Ok, so this didn’t appear when I searched it (figures), but did appear in the “Related Posts” section after I posted this topic. Turns out the answer was, in fact, pretty simple: How to sum every element but one - #3 by greg_plowman
Note that this works because false is a “strong zero” in Julia:
julia> false * Inf
0.0
julia> false * NaN
0.0
Beware that the more obvious code j != i ? inv(x[i]-x[j]) : 0 is type-unstable (while using 0.0 for the other branch assumes Float64 precision rather than inferring the precision from x).
All-in-all, the “one-liner” solutions seem less clear than a nested loop, though they do have the advantage that sum uses pairwise summation for improved accuracy. map also infers the result type for you, whereas if you use zeros approach you would need to do a type computation like y = zeros(typeof(inv(oneunit(eltype(x)))), length(x)) if you want the code to be type-generic.