Difference between Array and Vector

梦想与她 提交于 2020-04-13 07:34:53

问题


Is there a difference between Array and Vector?

typeof(Array([1,2,3]))
Vector{Int64}

typeof(Vector([1,2,3]))
Vector{Int64}

Both seem to create the same thing, but they are not the same:

Array == Vector
false

Array === Vector
false

So, what is actually the difference?


回答1:


The difference is that Vector is a 1-dimensional Array, so when you write e.g. Vector{Int} it is a shorthand to Array{Int, 1}:

julia> Vector{Int}
Array{Int64,1}

When you call constructors Array([1,2,3]) and Vector([1,2,3]) they internally get translated to the same call Array{Int,1}([1,2,3]) as you passed a vector to them.

You would see the difference if you wanted to pass an array that is not 1-dimensional:

julia> Array(ones(2,2))
2×2 Array{Float64,2}:
 1.0  1.0
 1.0  1.0

julia> Vector(ones(2,2))
ERROR: MethodError: no method matching Array{T,1} where T(::Array{Float64,2})

Also note the effect of:

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

julia> Vector(x)
3-element Array{Int64,1}:
 1
 2
 3

julia> Vector(x) === x
false

So essentially the call Vector(x) makes a copy of x. Usually in the code you would probably simply write copy(x).

A general rule is that Array is a parametric type that has two parameters given in curly braces:

  • the first one is element type (you can access it using eltype)
  • the second one is the dimension of the array (you can access it using ndims)

See https://docs.julialang.org/en/v1/manual/arrays/ for details.




回答2:


Vector is an alias for a one-dimensional Array. You can see that in the Julia REPL:

julia> Vector
Array{T, 1} where T

julia> Vector{Int32}
Array{Int32, 1}

Similarly, a Matrix is a 2-dimensional Array:

julia> Matrix
Array{T,2} where T


来源:https://stackoverflow.com/questions/61171531/difference-between-array-and-vector

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!