Julia Arrays
An array is a collection of elements of the same data type arranged in a certain order; it can be one-dimensional or multidimensional.
Julia arrays are mutable type collections used for lists, vectors, tables, and matrices.
Julia array indices start at 1 (not 0), and the array size is not fixed and can grow dynamically.
Julia arrays are specified with square brackets [...], with multiple elements separated by commas ,. The syntax to create a one-dimensional array (i.e. a vector) is:
[A, B, C, ...]
Create a one-dimensional array
The following example creates a simple one-dimensional array:
Example
julia
arr =
[
1
,
2
,
3
]
3
-element
Vector
{
Int64
}
:
1
2
3
In the example above we created a one-dimensional array with 3 elements, each a 64-bit integer.
Array elements can also have different types, in which case the element type becomes Any:
Example
julia
arr =
[
1
,
"RUNOOB"
,
2.5
, pi
]
4
-element
Vector
{
Any
}
:
1
"RUNOOB"
2.5
π =
3.1415926535897
...
Note:Arrays with element type Any have poorer performance (each element is a pointer and cannot be stored compactly); in real development you should keep array element types consistent whenever possible, seePerformance Tipssection.
Of course you can also force a specific type:
Example
julia
arr =
Int64
[
1
,
2
,
3
]
3
-element
Vector
{
Int64
}
:
1
2
3
julia
arr2 =
String
[
"Taobao"
,
"RUNOOB"
,
"GOOGLE"
]
3
-element
Vector
{
String
}
:
"Taobao"
"RUNOOB"
"GOOGLE"
We can also create an empty array:
Example
julia
arr =
Int64
[
]
Int64
[
]
julia
arr2 =
String
[
]
String
[
]
Index access
The created array can be accessed directly using index values; the first value has index 1 (not 0), and the last can be represented with end:
Example
julia
arr =
Int64
[
1
,
2
,
3
]
;
julia
arr
[
2
]
2
julia
arr
[
end
]
3
Range indexing to extract a subarray
julia
arr
[
1
:
2
]
2
-element
Vector
{
Int64
}
:
1
2
Specify the array type and dimensions
We can also use the following syntax to specify the type and dimensions of an array:
Array{type}(undef, dims...)
undef indicates the array is uninitialized.
dims... can be a tuple of dimensions, or several integer arguments.
Example
julia
array =
Array
{
Int64
}
(
undef,
3
)
One-dimensional array, 3 elements
3
-element
Vector
{
Int64
}
:
4834342704
4377305096
0
julia
array =
Array
{
Int64
}
(
undef,
3
,
3
,
3
)
3-dimensional array, 3 elements in each dimension
3
×
3
×
3
Array
{
Int64
,
3
}
:
[
:, :,
1
]
=
4562265712
0
0
...
undef is used to set the array as uninitialized to any known value, which is why we get random numbers in the output. An uninitialized array must be assigned before it can be safely read.
Creating two-dimensional arrays and matrices
We can omit the commas between array elements or use two semicolons ;; to create a two-dimensional array:
Example
julia
[
1
2
3
4
]
1
×
4
Matrix
{
Int64
}
:
1
2
3
4
julia
[
1
;;
2
;;
3
;;
4
]
1
×
4
Matrix
{
Int64
}
:
1
2
3
4
Even with only one row it is still a two-dimensional array, because Julia only recognizes column vectors, not so-called row vectors.
To add another row, just add a semicolon ;:
Example
julia
[
1
2
;
3
4
]
2
×
2
Matrix
{
Int64
}
:
1
2
3
4
You can also use a colon : and spaces to do this:
Example
julia
[
1
:
2
3
:
4
]
2
×
2
Matrix
{
Int64
}
:
1
3
2
4
We can also embed multiple one-dimensional arrays of equal length inside the square brackets, separated by spaces, to create a two-dimensional array:
Example
julia
[
[
1
,
2
]
[
3
,
4
]
[
5
,
6
]
]
2
×
3
Matrix
{
Int64
}
:
1
3
5
2
4
6
julia
[
[
1
2
]
;
[
3
4
]
;
[
5
6
]
]
3
×
2
Matrix
{
Int64
}
:
1
2
3
4
5
6
Concatenation functions hcat / vcat / cat
The spaces and semicolons inside the square brackets above are actually syntactic sugar for hcat (horizontal concatenation) and vcat (vertical concatenation); more general concatenation uses the cat function:
| Syntax | Equivalent function | Description |
|---|---|---|
[A; B; C] |
vcat(A, B, C) |
Concatenate along the first dimension (vertically) |
[A B C] |
hcat(A, B, C) |
Concatenate along the second dimension (horizontally) |
[A B; C D] |
hvcat(A, B, C, D) |
Concatenate both vertically and horizontally |
cat(A, B; dims=k) |
Concatenate along the k-th dimension, the most general |
Example
julia
vcat
(
[
1
,
2
]
,
[
3
,
4
]
)
4
-element
Vector
{
Int64
}
:
1
2
3
4
julia
hcat
(
[
1
,
2
]
,
[
3
,
4
]
)
2
×
2
Matrix
{
Int64
}
:
1
3
2
4
julia
cat
(
[
1
2
]
,
[
3
4
]
;
dims=
3
)
Concatenate along the third dimension into a 3-dimensional array
2
×
2
×
2
Array
{
Int64
,
3
}
:
[
:, :,
1
]
=
1
2
...
Using range functions to create arrays
Ellipsis ...
You can use the ellipsis ... to expand a range into an array:
Example
julia
[
0
:
10
...
]
11
-element
Vector
{
Int64
}
:
0
1
2
3
4
5
6
7
8
9
10
The collect() function
The collect() function has the following syntax:
collect(start:step:stop)
start is the starting value, step the step size, stop the ending value; the function returns an array:
Example
julia
collect
(
1
:
2
:
13
)
7
-element
Vector
{
Int64
}
:
1
3
5
7
9
11
13
The collect() function can also specify the element type:
Example
julia
collect
(
Float64
,
1
:
2
:
5
)
3
-element
Vector
{
Float64
}
:
1.0
3.0
5.0
The range() function
The range() function can generate an interval range with a specified step, convenient for collect() calls:
Example
julia
range
(
1
,
length
=
100
)
1
:
100
julia
range
(
1
, stop=
100
)
1
:
100
julia
range
(
1
, step=
5
,
length
=
100
)
1
:
5
:
496
julia
range
(
1
,
10
,
length
=
101
)
1.0
:
0.09
:
10.0
julia
range
(
start
=
1
, step=
1
, stop=
10
)
1
:
1
:
10
If the length is not specified and stop - start is not an integer multiple of step, a range ending before stop is generated:
julia> range(1, 3.5, step=2)
1.0:2.0:3.0
Creating arrays with range() and collect():
Example
julia
collect
(
range
(
1
, stop=
10
)
)
10
-element
Vector
{
Int64
}
:
1
2
3
4
5
6
7
8
9
10
Note:range returns a lazy Range object rather than an array; it stores only three numbers (start, step, length) and uses no memory no matter how large the interval. Most places that accept arrays also accept Range; only call collect when you actually need an array.
Creating arrays with comprehensions and generators
Another useful way to create arrays is to use comprehensions, with the following syntax:
A = [ F(x,y,...) for x=rx, y=ry, ... ]
Example
julia
[
n^
2
for
n
in
1
:
5
]
5
-element
Vector
{
Int64
}
:
1
4
9
16
25
Two-variable comprehension to create a two-dimensional array
julia
[
n
m
for
n
in
1
:
3
, m
in
1
:
3
]
3
×
3
Matrix
{
Int64
}
:
1
2
3
2
4
6
3
6
9
You can also write a comprehension without square brackets, producing an object called a generator:
Example
julia
collect
(
n^
2
for
n
in
1
:
5
)
5
-element
Vector
{
Int64
}
:
1
4
9
16
25
The generator does not allocate intermediate arrays, summing the sequence directly
julia
sum
(
1
/n^
2
for
n=
1
:
1000
)
1.6439345666815615
Basic array functions
| function | Description |
|---|---|
eltype(A) |
A the type of elements in |
length(A) |
A the number of elements in |
ndims(A) |
A the number of dimensions of |
size(A) |
a folder containing a A a tuple of the number of elements in each dimension |
size(A, n) |
A The n the number of elements in dimension |
axes(A) |
a folder containing a A a tuple of valid indices |
eachindex(A) |
an efficient iterator that accesses A each position in |
stride(A, k) |
in the k -th dimension, the index distance between adjacent elements |
Example
julia
A =
[
1
2
3
;
4
5
6
]
;
julia
size
(
A
)
(
2
,
3
)
julia
ndims
(
A
)
2
julia
length
(
A
)
6
julia
eltype
(
A
)
Int64
Construction and initialization functions
Julia provides many functions for constructing and initializing arrays. For most functions the first argument denotes the element type T of the array, defaulting to Float64 if omitted:
| function | Description |
|---|---|
Array{T}(undef, dims...) |
an uninitialized dense Array |
zeros(T, dims...) |
an all-zero Array |
ones(T, dims...) |
an array whose elements are all 1 Array |
trues(dims...) |
an array in which every element is true 's BitArray |
falses(dims...) |
an array in which every element is false 's BitArray |
reshape(A, dims...) |
an array containing the same data as A but with different dimensions |
copy(A) |
copy A |
deepcopy(A) |
deep copy, recursively copying its elements |
similar(A, T, dims...) |
The difference between A an uninitialized array of the same type but with a specified element type and dimensions |
reinterpret(T, A) |
The difference between A an array with the same binary data but element type T |
rand(T, dims...) |
a random array with elements uniformly distributed over [0, 1) (floating-point type) |
randn(T, dims...) |
a random array with elements from the standard normal distribution |
Matrix{T}(I, m, n) |
an m-by-n identity matrix (requires first using LinearAlgebra) |
fill!(A, x) |
fill with the value x fill the array A(in-place modification) |
fill(x, dims...) |
a new x array filled with the value Array |
zeros() Examples of creating arrays:
Example
julia
zeros
(
Int8
,
2
,
3
)
2
×
3
Matrix
{
Int8
}
:
0
0
0
0
0
0
julia
zeros
(
(
2
,
3
)
)
If no type is specified it defaults to Float64
2
×
3
Matrix
{
Float64
}
:
0.0
0.0
0.0
0.0
0.0
0.0
Adding, deleting, and modifying elements
Julia arrays are resizable; the most commonly used add/remove functions carry an exclamation-mark suffix (indicating in-place modification):
| function | Description |
|---|---|
push!(A, x) |
Add element x to the end of the array |
pop!(A) |
Remove and return the element at the end of the array |
pushfirst!(A, x) |
Insert element x at the beginning of the array |
popfirst!(A) |
Remove and return the element at the beginning of the array |
append!(A, B) |
Append all elements of collection B to the end of A |
insert!(A, i, x) |
Insert element x at the i-th position |
deleteat!(A, i) |
Delete the element at the i-th position |
splice!(A, i) |
Delete and return the element at the i-th position |
resize!(A, n) |
Resize the array to length n |
empty!(A) |
Empty the array |
Example
julia
arr =
Int64
[
]
;
julia
push
!
(
arr,
1
)
Add at End
1
-element
Vector
{
Int64
}
:
1
julia
append
!
(
arr,
[
2
,
3
]
)
Append multiple
3
-element
Vector
{
Int64
}
:
1
2
3
julia
pushfirst
!
(
arr,
0
)
Insert at the beginning
4
-element
Vector
{
Int64
}
:
0
1
2
3
julia
pop
!
(
arr
)
Pop the end
3
julia
insert
!
(
arr,
2
,
99
)
Insert at the 2nd position
4
-element
Vector
{
Int64
}
:
0
99
1
2
julia
deleteat
!
(
arr,
2
)
Delete the 2nd element
3
-element
Vector
{
Int64
}
:
0
1
2
Note:Do not use
arr = push!(arr, 1)this form (though the result is correct); push! already modifies arr in place, so just call it directly. Also do not writearr = [arr; 1]to add elements, it copies the entire array every time, which is poor for performance.
Modifying elements and broadcasting
To modify a single element use direct indexed assignment; for batch modification use dotted assignment .=:
Example
julia
A =
[
1
,
2
,
3
]
;
julia
A
[
1
]
=
100
;
julia
A
3
-element
Vector
{
Int64
}
:
100
2
3
.= broadcast assignment: add 10 to all elements (in-place, no new array created)
julia
A .+=
10
3
-element
Vector
{
Int64
}
:
110
12
13
You can also broadcast-assign to a subset of elements
julia
A
[
1
:
2
]
.=
0
2
-element view
(
::
Vector
{
Int64
}
,
1
:
2
)
with eltype
Int64
:
0
0
The broadcast mechanism combines arrays or scalars of different sizes element-wise; scalars are automatically "expanded":
Example
julia
a =
[
1.0
,
2.0
]
;
A =
[
1.0
2.0
;
3.0
4.0
]
;
Vector a added column-wise to matrix A
julia
a .+ A
2
×
2
Matrix
{
Float64
}
:
2.0
3.0
5.0
6.0
Any function can be broadcast
julia
string.
(
"item"
,
1
:
3
)
3
-element
Vector
{
String
}
:
"item1"
"item2"
"item3"
Performance tip:Nested dotted operations (such as
2 .* A .+ B) are fused into a single loop, producing no temporary arrays, so compared with2*A + B(which produces two temporary arrays) it is much faster; prefer dotted syntax.
Array operations
Operators supported by arrays:
| Category | operator | Description |
|---|---|---|
| Unary arithmetic | -, + |
element-wise negation, etc. |
| Binary arithmetic | - + * / \ ^ |
* is matrix multiplication, the rest are linear algebra operations |
| Dotted operations | .+ .* .- .^ |
element-wise operations |
| Comparison | ==, .== |
== compares whole arrays,.== element-wise comparison |
Example
julia
A =
[
1
2
;
3
4
]
;
B =
[
5
6
;
7
8
]
;
* is matrix multiplication
julia
A
B
2
×
2
Matrix
{
Int64
}
:
19
22
43
50
.* is element-wise multiplication
julia
A .
B
2
×
2
Matrix
{
Int64
}
:
5
12
21
32
== compares whether whole arrays are equal, returning a boolean
julia
A ==
[
1
2
;
3
4
]
true
.== compares element-wise, returning a boolean array
julia
A .== B
2
×
2
BitMatrix:
0
0
0
0
Common aggregation functions
Example
julia
A =
[
1
,
2
,
3
,
4
]
;
julia
sum
(
A
)
, prod
(
A
)
(
10
,
24
)
julia
maximum
(
A
)
,
minimum
(
A
)
(
4
,
1
)
julia
argmax
(
A
)
, argmin
(
A
)
position of the maximum/minimum value
(
4
,
1
)
julia
mean
(
A
)
The mean requires using Statistics
2.5
julia
sort
(
[
3
,
1
,
2
]
)
3
-element
Vector
{
Int64
}
:
1
2
3
Aggregate along dimensions; dims=1 means summing by column
julia
sum
(
[
1
2
;
3
4
]
, dims=
1
)
1
×
2
Matrix
{
Int64
}
:
4
6