Matrix indexing and manipulation

Hello there! I’m quite new to Julia and facing following issue: assume that we have a matrix:

mat = [1 2 3 4; 2 3 4 5]

and I want to manipulate a single value from a part of the matrix like this:

mat[1:3,1:3][1] = 2

then Julia would create a view and not modify the value in my original matrix mat. Up until now I worked around like this:

temporaryMat = mat[1:3,1:3] => temporaryMat[1] = 2 => mat[1:3,1:3] = temporaryMat.

I am well aware, that in this case I could have just manipulated the first value of our original mat. However I am currently working with a three-dimensional Matrix and I want to manipulate individual values.
I find this Solution to be rather inelegant.
So my question:
is there a way to achieve this with only one command?
I am really looking forward to an answer and thank you all in advance.

When you say “Julia would create a view” you’ve got it the wrong way around - it’s precisely the fact that Julia doesn’t create a view but a copy when you do mat[1:3, 1:3] that what you’re trying fails.

You can get around this by explicitly creating a view:

julia> @view(mat[1:2, 1:2])[1] = 5

julia> mat
2×4 Matrix{Int64}:
 5  2  3  4
 2  3  4  5

Thank you so much for the quick answer, it helps me a lot.
Have a nice day, sir!

1 Like