Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Julia: join two matrices using the same memory

Tags:

arrays

julia

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.

like image 875
4lrdyD Avatar asked Feb 24 '26 03:02

4lrdyD


2 Answers

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
like image 142
Jun Tian Avatar answered Feb 26 '26 18:02

Jun Tian


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
like image 33
Jamie P Avatar answered Feb 26 '26 17:02

Jamie P