Julia的陣列功能

lt發表於2017-04-04

1.陣列的定義及初始化,陣列元素也可以是陣列

i=sqrt(1/2)
p=[
[i,0],[1+i,0],
[0,i],[1+2i,i],
[0,1+i],[1+2i,1+i],
[i,1+2i],[1+i,1+2i]
]

2.陣列可以直接運算得到另一個陣列,而不用對每個元素運算

julia> p[1]-p[2]+p[4]
2-element Array{Float64,1}:
 1.41421
 0.707107

3.陣列長度必須預先規定,然後才能引用。陣列中第一個元素列出的型別,決定了後面元素的型別

np=[[0.0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0]]
9-element Array{Array{Float64,1},1}:
 [0.0,0.0]
 [0.0,0.0]
 [0.0,0.0]
 [0.0,0.0]
 [0.0,0.0]
 [0.0,0.0]
 [0.0,0.0]
 [0.0,0.0]
 [0.0,0.0]

np[1]=p[1]-p[2]+p[4]

julia> l=[]
0-element Array{Any,1}
       l[c]=[a,b]

ERROR: BoundsError: attempt to access 0-element Array{Any,1} at index [1]

4.幫助文件裡的陣列定義


help?> Array
search: Array SubArray BitArray DenseArray StridedArray pointer_to_array SharedArray SparseArrays takebuf_array

  Array(dims)

  Array{T}(dims) constructs an uninitialized dense array with element type T. dims may be a tuple or a series of
  integer arguments. The syntax Array(T, dims) is also available, but deprecated.

julia> b=Array{Int}(5)
5-element Array{Int32,1}:
 0
 0
 0
 0
 0

5.沒有明確初始化的陣列的值不定

julia> x=Array{Int}(15);

julia> x[1]
83

julia> x
15-element Array{Int32,1}:
  83
 116
 114
 105
 100
 101
 100
  77
  97
 116
 114
 105
 120
   0
   0

6.可以用map初始化,比迴圈好看

julia> map(x->b[x]=0,1:10)
10-element Array{Int32,1}:
 0
 0
 0
 0
 0
 0
 0
 0
 0
 0

julia> b
15-element Array{Int32,1}:
   0
   0
   0
   0
   0
   0
   0
   0
   0
   0
 105
 118
 101
   0
   0

6.作為陣列元素的陣列,其長度可以不同.整數陣列可以賦值給浮點數陣列

julia> c=Array{Array{Float64,1}}(15)
15-element Array{Array{Float64,1},1}:
 #undef
 #undef
 #undef
 #undef
 #undef
 #undef

julia> c[1]=[1.1,2.2]
2-element Array{Float64,1}:
 1.1
 2.2

julia> c[2]=[2,3,4,5]
4-element Array{Int32,1}:
 2
 3
 4
 5

julia> c
15-element Array{Array{Float64,1},1}:
    [1.1,2.2]
    [2.0,3.0,4.0,5.0]
 #undef

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

相關文章