a = [1 2 3 4 5]
I want to replace entries 4 and 5( > 3) with 10.
I tried a > 3
. Did not work out.
How to do this in Julia?
Related qn: Logical Indexing in Julia
You can do:
julia> a = [1 2 3 4 5]
1×5 Matrix{Int64}:
1 2 3 4 5
julia> a[a .> 3] .= 10
2-element view(::Vector{Int64}, [4, 5]) with eltype Int64:
10
10
julia> a
1×5 Matrix{Int64}:
1 2 3 10 10
or
julia> a
1×5 Matrix{Int64}:
1 2 3 4 5
julia> replace(x -> x > 3 ? 10 : x, a) # allocates a new array
1×5 Matrix{Int64}:
1 2 3 10 10
julia> a # a is unchanged
1×5 Matrix{Int64}:
1 2 3 4 5
julia> replace!(x -> x > 3 ? 10 : x, a) # updates the array in place
1×5 Matrix{Int64}:
1 2 3 10 10
julia> a # a is updated in place
1×5 Matrix{Int64}:
1 2 3 10 10
If you need to do this operation many times on large a array (e.g. inside a hot loop in some function that you call many times) then using replace!
will be a faster option.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With