Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to unpack multidimensional array into variables in Julia

In Python I can do:

a = array([[1,2],[3,4]])
row1, row2 = a

Is there an equivalent one-liner in Julia? This doesn't seem to work:

a = [[1 2]; [3 4]]
row1, row2 = a

Instead it sets row1=1 and row2=3. Thanks!

like image 956
marius Avatar asked Oct 22 '25 03:10

marius


2 Answers

Depending on what you are doing you could use a Vector{Vector{T}}, like python list of lists instead of a Matrix (Array{T,2}).

In v0.5+ it just works, with [ , ]:

julia> VERSION
v"0.5.0-dev+4440"

julia> a = [[1, 2], [3, 4]]
2-element Array{Array{Int64,1},1}:
 [1, 2]
 [3, 4]

julia> a = [[1, 2]; [3, 4]]
4-element Array{Int64,1}:
 1
 2
 3
 4

julia> row1, row2 = a;

julia> (row1, row2)
(2-element Array{Int64,1}:
 1
 2,2-element Array{Int64,1}:
 3
 4)

In v0.4+ you need to type the array as an array of arrays, like so:

julia> VERSION
v"0.4.5"

julia> a = Vector[[1, 2], [3, 4]]
2-element Array{Array{T,1},1}:
 [1,2]
 [3,4]

julia> b = [[1, 2]; [3, 4]]
4-element Array{Int64,1}:
 1
 2
 3
 4

julia> c = [[1, 2], [3, 4]]
WARNING: [a,b] concatenation is deprecated; use [a;b] instead
 in depwarn at deprecated.jl:73
 in oldstyle_vcat_warning at abstractarray.jl:29
 in vect at abstractarray.jl:32
while loading no file, in expression starting on line 0
4-element Array{Int64,1}:
 1
 2
 3
 4

julia> row1, row2 = a;

julia> row1, row2
([1,2],[3,4])
like image 116
HarmonicaMuse Avatar answered Oct 24 '25 17:10

HarmonicaMuse


The shortest one-liner I can think of in Julia is

r1, r2 = [sub(a, i, :) for i=1:2]

it's not as efficient as writing out

r1 = sub(a, 1, :)
r2 = sub(a, 2, :)

because the first version creates a temporary array and then unpacks it into the tuple on the left hand side.

Note:

New versions of NumPy (1.10 or so) now returns views of arrays, not copies. In Julia 0.4, views are created by sub, and copies are created by slicing. So in Julia

r1 = a[1,:]

is not equivalent to the analogous NumPy/Python statement

r1 = a[0,:]

The main difference between views and copies is that changing the entries of a will change the entries of r1 if r1 is a view, but not if r1 is a copy. The disadvantage of copies is that they take up more memory.

like image 32
Jiahao Chen Avatar answered Oct 24 '25 17:10

Jiahao Chen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!