Increase value of element in array. Like setindex!, but addition

Sometimes I have an array, and want to pass a copy of the array into a function, but updated, e.g.

function my_array_function(array)
    do_something_else_function(setindex!(copy(array),0.,1))
end

this is basically a shorthand for

function my_array_function(array)
    new_array = copy(array)
    new_array[1] = 0.
    do_something_else_function(new_array)
end

Howevever, sometimes I don’t know what the target index is, and simply want to increase it by some number, e.g. I want

function my_array_function(array)
    new_array = copy(array)
    new_array[1] += 1.
    do_something_else_function(new_array)
end

is there a similar

function my_array_function(array)
    do_something_else_function(addindex!(copy(array),0.,1))
end

to make this shorter?

I take it that you don’t want to make your own addindex! function for some reason?

function addindex!(a, idx, v)
      b = copy(a)
      b[idx] += v
      return b
end
3 Likes

Something like updateindex! has been discussed, see e.g. https://github.com/JuliaLang/julia/issues/15630.

As of now you have to write your own little convenience function though.

2 Likes

Thanks, both for the help :slight_smile: