4lrdyD
4lrdyD

Reputation: 433

Julia: join two matrices using the same memory

I want to fuse two arrays without using more memory, it's posible?, for instance:

a=[1 2 3
   4 5 6
   7 8 9]
b=[11 12 13
   14 15 16
   17 18 19]

I need to get the array:

c=[a b]

but using the same memory as a and b, i.e, any change in a or b must be reflected in c.

Upvotes: 3

Views: 224

Answers (2)

Jamie P
Jamie P

Reputation: 115

If you start in reverse, define C first

julia> C = rand(0:9, 3, 6)
3×6 Array{Int64,2}:
 3  2  4  4  9  8
 8  8  6  5  5  9
 0  7  5  8  7  5

then have A and B be views of C

julia> A = @view C[:, 1:3]
3×3 view(::Array{Int64,2}, :, 1:3) with eltype Int64:
 3  2  4
 8  8  6
 0  7  5

julia> B = @view C[:, 4:6]
3×3 view(::Array{Int64,2}, :, 4:6) with eltype Int64:
 4  9  8
 5  5  9
 8  7  5

then it works.

julia> A[2,2] = -1
-1

julia> C
3×6 Array{Int64,2}:
 3   2  4  4  9  8
 8  -1  6  5  5  9
 0   7  5  8  7  5

Upvotes: 1

Jun Tian
Jun Tian

Reputation: 1390

There's also another package CatViews.jl

julia> x = CatView(a, b);   # no copying!!!

julia> reshape(x, size(a, 1), :)
3×6 reshape(::CatView{2,Int64}, 3, 6) with eltype Int64:
 1  2  3  11  12  13
 4  5  6  14  15  16
 7  8  9  17  18  19

Upvotes: 4

Related Questions