Assignement in matrixes using double indexes

Viewed 46

I can't figure out how to obtain this behavior:

From this matrix:

julia> a = [1 1 1; 1 1 1; 1 1 2]
3×3 Array{Int64,2}:
 1  1  1
 1  1  1
 1  1  2

I want to change all the 1s to 5s but only in the last row.

What I did is a[3, :][a[3, :] .== 1] .= 5 but the value of a isn't changed.

I've noticed that with:

foo[foo .== 1] .= 5
a[3,  :] = foo

It works, but I'm trying to reduce allocations and this should be removed.

Thanks in advance

2 Answers

You can use @view and replace!:

julia> a = [1 1 1
            1 1 1
            1 1 2]
3×3 Array{Int64,2}:
 1  1  1
 1  1  1
 1  1  2

julia> replace!(@view(a[end, :]), 1 => 5)
3-element view(::Array{Int64,2}, 3, :) with eltype Int64:
 5
 5
 2

julia> a
3×3 Array{Int64,2}:
 1  1  1
 1  1  1
 5  5  2

The problem is a[3, :][a[3, :] .== 1] .= 5 is the same as getindex(a, 3, :)[a[3, :] .== 1] .=5

getindex returns a copy of that part of a You are mutating the copy, not the original a

You want to use a view view(a, 3, :)[a[3, :] .== 1] .=5

You can also do this with the @view or @views macro.

Related