Simple matrix operations
We will be meeting matrices and matrix operations throughout this book, but let us look now at the simplest of operations.
Let’s take A
and B
, as defined in the following code snippet:
julia>
A = [1 2 3; 4 5 6];julia>
B = [1 5; 4 3; 2 6];
The normal matrix rules apply, which is a feature of multiple dispatch; we will cover this in Chapter 4.
The transpose of B
can be computed as follows:
julia>
C = transpose(B)
2×3 transpose(::Matrix{Int64}) with eltype Int64
1 4 2
5 3 6
This can also be written more compactly as C = B’:
julia>
A + C 2x3 Matrix{Int64}: 2 6 5 9 8 12julia>
A*B 2x2 Matrix{Int64}: 15 29 36 71
Matrix division makes more sense with square matrices, but it is possible to define the operations for non-square matrices too. Note here that the /
and \
operations produce results of different sizes:
julia>
A / C 2x2 Matrix{Float64} 0.332273 0.27663 0.732909 0.710652julia>
A \ C 3x3 Matrix{Float64}: 1.27778 -2.44444 0.777778 0.444444 -0.111111 0.444444 -0.388889 2.22222 0.111111
The type of the array was previously defined as Array{Int64,2}
rather than the now more compact form of Matrix{Int64}
, and ditto Array{Float64,2}
has been replaced with Matrix{Float64}
.
We will discuss matrix decomposition in more detail later when looking at linear algebra.
Although A * C
is not allowed because the number of columns of A
is not equal to the number of rows of C
, the following broadcasts are all valid:
julia>
A .* C 2x3 Matrix{Int64}: 1 8 6 20 15 36julia>
A ./ C 2x3 Matrix{Float64}: 1.0 0.5 1.5 0.8 1.66667 1.0julia>
A .== C 2x3 BitMatrix 1 0 0 0 0 1
So far, we have only been looking at manipulating variables representing arithmetic values. Julia has a variety of string types, which we will look at next.