# How to sum every element but one

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]`

6 Likes

`sum(x[i] for i in I if i != j)`

4 Likes

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.

5 Likes

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)
``````
3 Likes