Mapping vector elements

Hi, I am defining the gradients by using below code but i want to make negative values to zero. I wrote below code but it is not working. could you please help me to modify this

function gf_p(p0::Vector, grad::Vector; r, β, η, fem_params)
    if length(grad) > 0
        dgdp, = Zygote.gradient(p -> gf_p(p; r, β, η, fem_params), p0)
        grad[:] = dgdp
    end
    map(x-> grad[:]<0 , 0)
    -grad
end

thank you

Among other oddities, you’re discarding the value of this expression.

One way to set negative values to zero is with the code

x[x .< 0] .= 0

map on its own will not modify the values in place.

2 Likes

thank you very much! it is working.

You could also do

x .= max.(x, 0)

which should be faster, since it doesn’t create any temporary array.

And this

should probably be replaced with

grad .= dgdp

Actually, why do you need to modify grad? Isn’t it better to just work on dgdp without copying the data into grad?

what do you mean by modifying dgdp? It seems that there are some errors in calculating the gradients by zygot and they are very small so i want to make them as zero.