Array Operations

by Martin D. Maas, Ph.D

Perform basic operations with multidimensional arrays, like matrix multiplication and dot product.

Now that we know several ways of inputting arrays, we should take a look at how we can operate with them.

Matrix multiplication

Two dimensional arrays (or matrices) are a fundamental part of Julia. For example, you can resort to a Matlab-style syntax for matrix-matrix multiplication:

A * B

A Matrix and a Vector can be also multiplied with the * operator.

A * v

Element-wise multiplication

In case you need to multiply the elements of an n-dimensional array on an element-wise fashion, you can resort to the dot operator, which will broadcast the scalar multiplication operator on an element-wise fashion, just as we discussed in the previous post of this tutorial series:

A .* B

Dot product

You can do dot products by calling the dot function

v = rand(1000)
w = rand(1000)
z = dot(v,w)

Alternatively, you can resort to a typical linear algebra notation:

z = v'w

Backslash operator

Just like in Matlab, Julia has a built-in operator to solve matrices. For square matrices, it will try to solve the linear system, while for rectangular matrices, it will seek for the least squares solution.

One ‘gotcha’ that you will probably encounter sooner or later is that, as 1xN matrices are not the same as N-element vectors. We have to be careful and always employ vectors in the right-hand side of an equation.

b1 = [4.0, 5, 6]                # 3-element Vector{Float64}
b2 = [4.0; 5; 6]                # 3-element Vector{Float64}
m1 = [4.0 5 6]                  # 1×3 Matrix{Float64}

x=A\b1                          # Solves A*x=b
x=A\b2                          # Solves A*x=b  
x=A\m1                          # Error!!