Hi. I would like to do the following:
julia> c = [1,2,3,4,5,6];
julia> a = c[1:3];
julia> a[1] = 10;
julia> c
6-element Vector{Int64}:
10
2
3
4
5
6
However the last evaluation yields [1,2,3,4,5,6]
.
How can I use shallow reference for a
?
Also
Ref
and Ptr
considered good practice ?In julia, array slicing creates a copy instead of a view. You just need to do a = @view c[1:3]
and it should work fine. (Or a = view(c, 1:3)
if you prefer).
julia> a = @view c[1:3];
julia> a[1] = 10;
julia> c
6-element Vector{Int64}:
10
2
3
4
5
6
thanks! is there any way I can do the opposite ? That is:
julia> a = [1,2,3];
julia> b = [4,5,6];
julia> c = [@view(a[1:end])...,@view(b[1:end])...]; #something similar here
julia> c[1] = 10;
julia> a
3-element Vector{Int64}:
10
2
3
Now a=[1,2,3]
, but I would like that to be [10,2,3]
.
I haven't used it myself, but I believe you're looking for the mortar
function from BlockArrays.jl. If not, it might be in LazyArrays.jl.
If neither have it, implementing yourself should only be a couple hours work. The basic approach is to create a wrapper struct around either an array of arrays or ntuple of arrays depending on your requirements and then implement the array interface on your new type so that it passes through.
Filippos Christou said:
- Is the usage of
Ref
andPtr
considered good practice ?- I have some okey-ish background in C logic, but I never found any tutorial how to do such operations in julia. can you propose some resources ?
For most array manipulation in Julia, there's generally going to be a "better" way than doing transformations on raw Ptr
s/Ref
s, so it's generally good practice to avoid them. The big thing this gains you is composability within the package ecosystem since so many things work using the array interface from Base
. If you don't care about the arrays you're working with being compatible with the wider ecosystem and are confident in your ability to avoid incorrect pointer arithmetic (I'm not), working with pointers is always an option. :shrug: Julia isn't real big on keeping you from doing things even if they are bad ideas.
Last updated: Nov 06 2024 at 04:40 UTC