I want to sum every element of x[i] except when i = j. For example:
j=10
I = 1:30
sum(x[i] for i in I) #here I want to sum every element but j.
I want to sum every element of x[i] except when i = j. For example:
j=10
I = 1:30
sum(x[i] for i in I) #here I want to sum every element but j.
Thereās always the simple sum(x)-x[j]
sum(x[i] for i in I if i != j)
Unless āthe oneā element is problematic, e.g., itās NaN or much larger than the others, summing everything and then subtracting one element is probably the fastest method by far.
If the element is problematic, you could set it to 0 before summing, and then set it back afterwards.
a = randn(1000)
@btime sum($a) - $a[100] # 154.763 ns (0 allocations: 0 bytes)
@btime sum($a[i] for i in eachindex($a) if i != 100) # 4.415 μs (0 allocations: 0 bytes)
The first approach is much faster, but itās also much more accurate since it uses a highly accurate summing algorithm, which is not used in the second case.
This is what I needed, thanks.
Thanks.
Thank you for the explanation. I needed the second one.
Another direct approach, much faster than the generator:
@btime sum(i -> i == 100 ? 0. : @inbounds($a[i]), eachindex($a))
# 182.628 ns (0 allocations: 0 bytes)