Matrices and Multidimensional Arrays
Prerequisites: Arrays
Julia's arrays can have any number of dimensions. A two-dimensional
array is a Matrix. Spaces separate columns and semicolons separate
rows:
A = [1 2 3; 4 5 6]
display(A)
println(size(A), " ", size(A, 1), " ", ndims(A), " ", length(A))
println(typeof(A))
println(A[2, 3], " ", A[1, :], " ", A[:, 2])
println(A[end, end])
2×3 Matrix{Int64}:
1 2 3
4 5 6
(2, 3) 2 2 6
Matrix{Int64}
6 [1, 2, 3] [2, 5]
6
A[row, column]indexes;:alone means "all" of that dimension.A[1, :]is the first row andA[:, 2]the second column (both come back as vectors).displayshows the value the way the REPL does.
Creating matrices
display(zeros(2, 3))
display(reshape(1:6, 2, 3))
display([i + 10j for i in 1:2, j in 1:3])
display(hcat([1, 2], [3, 4]))
display(vcat([1 2], [3 4]))
2×3 Matrix{Float64}:
0.0 0.0 0.0
0.0 0.0 0.0
2×3 reshape(::UnitRange{Int64}, 2, 3) with eltype Int64:
1 3 5
2 4 6
2×3 Matrix{Int64}:
11 21 31
12 22 32
2×2 Matrix{Int64}:
1 3
2 4
2×2 Matrix{Int64}:
1 2
3 4
zeros(rows, cols),ones,rand,fill(value, rows, cols).- A comprehension with two loops separated by a comma makes a matrix.
hcatjoins side by side,vcatstacks vertically.
Column-major order
Julia stores matrices column by column (like Fortran and MATLAB,
unlike C and NumPy's default). reshape(1:6, 2, 3) above filled the
first column with 1, 2, then the second with 3, 4. For speed, loop with
the first index innermost:
function sum_by_columns(M)
s = zero(eltype(M))
for j in axes(M, 2), i in axes(M, 1) # i (rows) changes fastest
s += M[i, j]
end
return s
end
M = reshape(1.0:12.0, 3, 4)
println(sum_by_columns(M), " ", sum(M))
println(vec(M'))
78.0 78.0
[1.0, 4.0, 7.0, 10.0, 2.0, 5.0, 8.0, 11.0, 3.0, 6.0, 9.0, 12.0]
axes(M, 2) gives the valid indexes of dimension 2. vec flattens an
array into a vector (in column order); M' is the transpose.
Reductions along dimensions
scores = [90 85 77;
60 72 88]
println(sum(scores))
println(sum(scores, dims = 1))
display(sum(scores, dims = 2))
display(maximum(scores, dims = 2))
println(vec(sum(scores, dims = 2)))
472
[150 157 165]
2×1 Matrix{Int64}:
252
220
2×1 Matrix{Int64}:
90
88
[252, 220]
dims = 1 collapses the rows (one result per column); dims = 2
collapses the columns (one result per row). The result keeps its
dimensions, so use vec if you want a plain vector.
Views instead of copies
Slicing like A[:, 1] copies the data. A view refers to the
original instead:
A = [1 2; 3 4]
col = A[:, 1]
col[1] = 100
println(A)
v = view(A, :, 1)
v[1] = 100
println(A)
@views println(sum(A[2, :]))
[1 2; 3 4]
[100 2; 3 4]
7
Views avoid allocating memory in loops over large arrays; @views
turns every slice in an expression into a view.