In Julia, Arrays have types parametrized by two variables: a type T
and a dimensionality D
(Array{T, D}
). For a 1-dimensional array of integers, the type is:
julia> x = [1, 2, 3]; julia> typeof(x) Array{Int64, 1}
If the array is a 2-dimensional matrix, D
equals to 2:
julia> x = [1 2 3; 4 5 6; 7 8 9] julia> typeof(x) Array{Int64, 2}
The element type can also be abstract types:
julia> x = [1 2 3; 4 5 "6"; 7 8 9] 3x3 Array{Any,2}: 1 2 3 4 5 "6" 7 8 9
Here Any
(an abstract type) is the type of the resulting array.
Specifying Types when Creating Arrays
When we create an Array in the way described above, Julia will do its best to infer the proper type that we might want. In the initial examples above, we entered inputs that looked like integers, and so Julia defaulted to the default Int64
type. At times, however, we might want to be more specific. In the following example, we specify that we want the type to be instead Int8
:
x1 = Int8[1 2 3; 4 5 6; 7 8 9]
typeof(x1) ## Array{Int8,2}
We could even specify the type as something such as Float64
, even if we write the inputs in a way that might otherwise be interpreted as integers by default (e.g. writing 1
instead of 1.0
). e.g.
x2 = Float64[1 2 3; 4 5 6; 7 8 9]