Julia uses the standard mathematical meanings of arithmetic operations when applied to matrices. Sometimes, elementwise operations are desired instead. These are marked with a full stop (.
) preceding the operator to be done elementwise. (Note that elementwise operations are often not as efficient as loops.)
The +
operator on matrices is a matrix sum. It is similar to an elementwise sum, but it does not broadcast shape. That is, if A
and B
are the same shape, then A + B
is the same as A .+ B
; otherwise, A + B
is an error, whereas A .+ B
may not necessarily be.
julia> A = [1 2
3 4]
2×2 Array{Int64,2}:
1 2
3 4
julia> B = [5 6
7 8]
2×2 Array{Int64,2}:
5 6
7 8
julia> A + B
2×2 Array{Int64,2}:
6 8
10 12
julia> A .+ B
2×2 Array{Int64,2}:
6 8
10 12
julia> C = [9, 10]
2-element Array{Int64,1}:
9
10
julia> A + C
ERROR: DimensionMismatch("dimensions must match")
in promote_shape(::Tuple{Base.OneTo{Int64},Base.OneTo{Int64}}, ::Tuple{Base.OneTo{Int64}}) at ./operators.jl:396
in promote_shape(::Array{Int64,2}, ::Array{Int64,1}) at ./operators.jl:382
in _elementwise(::Base.#+, ::Array{Int64,2}, ::Array{Int64,1}, ::Type{Int64}) at ./arraymath.jl:61
in +(::Array{Int64,2}, ::Array{Int64,1}) at ./arraymath.jl:53
julia> A .+ C
2×2 Array{Int64,2}:
10 11
13 14
Likewise, -
computes a matrix difference. Both +
and -
can also be used as unary operators.
The *
operator on matrices is the matrix product (not the elementwise product). For an elementwise product, use the .*
operator. Compare (using the same matrices as above):
julia> A * B
2×2 Array{Int64,2}:
19 22
43 50
julia> A .* B
2×2 Array{Int64,2}:
5 12
21 32
The ^
operator computes matrix exponentiation. Matrix exponentiation can be useful for computing values of certain recurrences quickly. For instance, the Fibonacci numbers can be generated by the matrix expression
fib(n) = (BigInt[1 1; 1 0]^n)[2]
As usual, the .^
operator can be used where elementwise exponentiation is the desired operation.