Stream: helpdesk (published)

Topic: Ref help


view this post on Zulip Filippos Christou (Jan 31 2023 at 20:42):

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

view this post on Zulip Mason Protter (Jan 31 2023 at 20:58):

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).

view this post on Zulip Mason Protter (Jan 31 2023 at 20:58):

julia> a = @view c[1:3];

julia> a[1] = 10;

julia> c
6-element Vector{Int64}:
 10
  2
  3
  4
  5
  6

view this post on Zulip Filippos Christou (Jan 31 2023 at 21:21):

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].

view this post on Zulip Adam non-jedi Beckmeyer (Feb 01 2023 at 13:30):

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.

view this post on Zulip Adam non-jedi Beckmeyer (Feb 01 2023 at 13:35):

Filippos Christou said:

For most array manipulation in Julia, there's generally going to be a "better" way than doing transformations on raw Ptrs/Refs, 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: Oct 02 2023 at 04:34 UTC