🔖

# Julia 一次元配列の早見表

2022/12/23に公開1

## 配列の作成

``````julia> [2]
1-element Vector{Int64}:
2

julia> [2, 3, 5]
3-element Vector{Int64}:
2
3
5

julia> Float64[2, 3, 5] # Float64の型を指定する
3-element Vector{Float64}:
2.0
3.0
5.0
``````

## 等差数列

``````julia> Vector(1:10)
10-element Vector{Int64}:
1
2
3
4
5
6
7
8
9
10

julia> Vector(1:2:10)
5-element Vector{Int64}:
1
3
5
7
9

julia> Vector(10:-2:1)
5-element Vector{Int64}:
10
8
6
4
2

julia> [n^3 for n in 1:5]
5-element Vector{Int64}:
1
8
27
64
125
``````

## 任意の値で初期化する

``````julia> zeros(Int64, 3)
3-element Vector{Int64}:
0
0
0

julia> zeros(Float64, 3)
3-element Vector{Float64}:
0.0
0.0
0.0

julia> ones(3)
3-element Vector{Float64}:
1.0
1.0
1.0

julia> ones(Int64, 3)
3-element Vector{Int64}:
1
1
1

julia> fill(3, 5)
5-element Vector{Int64}:
3
3
3
3
3
``````

## 無作為な値で初期化する

``````julia> rand(3)
3-element Vector{Float64}:
0.47236299095759604
0.3452445121563541
0.4094982746475493

julia> rand(Int64, 3)
3-element Vector{Int64}:
4868806997068651585
-3864495101985943932
-4596634744543595203

julia> rand(["春は、あけぼの。", "夏は、夜。", "秋は、夕暮。", "冬は、つとめて。"], 7)
7-element Vector{String}:
"秋は、夕暮。"
"冬は、つとめて。"
"秋は、夕暮。"
"春は、あけぼの。"
"秋は、夕暮。"
"冬は、つとめて。"
"夏は、夜。"
``````

## 要素の取得

``````julia> vector = Vector(1:10)
10-element Vector{Int64}:
1
2
3
4
5
6
7
8
9
10

julia> vector[1]
1

julia> vector[begin]
1

julia> vector[10]
10

julia> vector[end]
10

julia> vector[1:3]
3-element Vector{Int64}:
1
2
3

julia> vector[begin:3]
3-element Vector{Int64}:
1
2
3

julia> vector[8:end]
3-element Vector{Int64}:
8
9
10
``````

## 要素の追加・削除

``````julia> vector = Vector(1:5)
5-element Vector{Int64}:
1
2
3
4
5

julia> push!(vector, 6)
6-element Vector{Int64}:
1
2
3
4
5
6

julia> pop!(vector)
6

julia> pushfirst!(vector, 0)
6-element Vector{Int64}:
0
1
2
3
4
5

julia> popfirst!(vector)
0

julia> insert!(vector, 2, 0)
6-element Vector{Int64}:
1
0
2
3
4
5

julia> deleteat!(vector, 2)
5-element Vector{Int64}:
1
2
3
4
5
``````

### Discussion

``````julia> @allocated Vector(1:10)
144

julia> typeof(Vector(1:10))
Vector{Int64} (alias for Array{Int64, 1})

julia> @allocated 1:10
0

julia> typeof(1:10)
UnitRange{Int64}
``````

ログインするとコメントできます