Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Logical/Boolean indexing of an array in Julia

Tags:

indexing

julia

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

like image 477
Vinod Avatar asked Dec 30 '22 12:12

Vinod


1 Answers

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.

like image 75
Bogumił Kamiński Avatar answered Jan 06 '23 16:01

Bogumił Kamiński