Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split array in Julia like in Python?

Tags:

arrays

julia

I want to do this :

a = [1,2,3,4,5]
print(a[:2])

The output is

[1, 2]

How can I do the same things in Julia? But my a is of type : Array{Array{Float64,1},1}

like image 828
Zul Huky Avatar asked Aug 11 '26 17:08

Zul Huky


1 Answers

Assume you have:

julia> x = [[i] for i in 1.0:5.0]
5-element Array{Array{Float64,1},1}:
 [1.0]
 [2.0]
 [3.0]
 [4.0]
 [5.0]

(this is an equivalent of you have written above but with the types you request).

You can slice x by passing the first and the last index of the slice. Both lower and upper bound will be included (also note that Julia uses 1-based indexing):

julia> x[1:2]
2-element Array{Array{Float64,1},1}:
 [1.0]
 [2.0]

julia> x[2:4]
3-element Array{Array{Float64,1},1}:
 [2.0]
 [3.0]
 [4.0]

You can use end to indicate end of your collection:

julia> x[3:end]
3-element Array{Array{Float64,1},1}:
 [3.0]
 [4.0]
 [5.0]

The above operations created a new vector. If you prefer to have a view then write:

julia> @view x[2:4]
3-element view(::Array{Array{Float64,1},1}, 2:4) with eltype Array{Float64,1}:
 [2.0]
 [3.0]
 [4.0]

or

julia> view(x, 2:4)
3-element view(::Array{Array{Float64,1},1}, 2:4) with eltype Array{Float64,1}:
 [2.0]
 [3.0]
 [4.0]

The difference is that with @view macro you can still use end, e.g. @view x[2:end], but view function does not support it.

like image 63
Bogumił Kamiński Avatar answered Aug 14 '26 11:08

Bogumił Kamiński



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!