1

I am trying to write a mutating function where the value passed as first argument mutates depending on the second one.

As an example, remove_when_zero_in_b below should return the values in vector a for those indexes where vector b is not 0.

"""filters 'a' when there is a zero in 'b'"""
function remove_when_zero_in_b!(a::AbstractVector, b::Vector{<:Real})
    a = a[b .!= 0]
    a
end

E.g.

x = [1.0, 2.0, 3.0, 4.0, 5.0]
y = [0,   1,   0,   2  , 0 ]

remove_when_zero_in_b!(x, y) # should mutate x

Then x should be:

println(x)
2-element Vector{Float64}:
 2.0
 4.0

However, the function above does not mutate x and remains as the initial vector with 5 elements.

What am I missing here? How would a function mutating x so I obtain the desired result look like?

Josep Espasa
  • 690
  • 5
  • 16
  • 1
    Does this answer your question? [Mutating function in Julia (function that modifies its arguments)](https://stackoverflow.com/questions/39293082/mutating-function-in-julia-function-that-modifies-its-arguments) – Shayan Mar 01 '22 at 08:06
  • I've marked this as a duplicate of the question @Shayan linked to, as it has an answer and a good explanation. One other method that that answer doesn't mention is `a .= a[b .!= 0]`, which would come useful when the array is multidimensional (i.e. not just a vector). – Sundar R Mar 01 '22 at 08:15
  • @SundarR Are you sure about `a .= a[b .!= 0]`? didn't work either. I replaced it with `a = a[b .!= 0]` and after executing function on `x` , `y`; `x` is still the same. – Shayan Mar 01 '22 at 08:19
  • 1
    @JosepEspasa probably the function you are looking for is `filter!`. – phipsgabler Mar 01 '22 at 08:21
  • 2
    @Shayan Yeah, I should have realized that it wouldn't work in this case - it only works when the array size doesn't change. For eg. it works with `a .= a.^2`. – Sundar R Mar 01 '22 at 08:21
  • @SundarR Exacto! – Shayan Mar 01 '22 at 08:22
  • Also, [These](https://stackoverflow.com/questions/35235597/julia-function-argument-by-reference), [2](https://stackoverflow.com/questions/65723373/why-wont-this-softmax-function-i-have-written-in-julia-change-the-input-data?rq=1) can help understand the material. – Shayan Mar 01 '22 at 08:27

1 Answers1

4

a = a[b .!= 0] create a new copy of a, you can write,

function remove_when_zero_in_b!(a::AbstractVector, b::Vector{<:Real})
    deleteat!(a, b .== 0)
    a
end