Chapter 10: Arrays

Return to all notes

Arrays are a fundamental data structure for nearly every computer language and it is a crucial for scientific computing therefore it is important for julia. It is recommended to read the julia documentation on arrays

In short an array is a collection of data of (typically) the same type under the same name. We have seen arrays before. For example, if we say

arr = [1,2,3]

Then we get a 1-dimensional array of length 3. Note that when returned, julia says 3-element Array{Int64,1}: which means

There are some basic functions that tell us some information:

Constructing arrays

We can create arrays in many ways. As seen above, the line

arr=[1,2,3]

creates a 1-D array of length 3. If we know the element, a 2D array can be made like:

arr2=[1 2 3; 4 5 6]

and this returns:

2×3 Array{Int64,2}:
 1  2  3
 4  6  7

and note that there is now a 2 after the comma in the {}. This indicates it is a 2 dimensional array.

The following built-in functions are also helpful:

Comprehensions

If we know the form of an array element, we can use what is called a comphrension to construct it in a compact manner. For example, a 1D array with the elements 1,-1,1,-1,1,-1 can be made:

[(-1)^n for n=0:7]

and the following:

[m+n for n=1:8,m=1:8]

makes an 8 by 8 matrix where each element is the sum of the row and column number.

Accessing elements of an array

Let

x=collect(1:7)

which is the vector of numbers 1,2 to 7. To access the 2nd element, we type x[2]. To get an array of the middle 3 elements, type

x[3:5]

or

x[3:end-2]

where end will automatically fill with the index of the last element.

Let

A=[i+j for i=1:4,j=1:5]

to access the 1st row, 3rd column, type A[1,3]. If you want the subarray of the first and 3rd and 5th columns and all rows type:

A[:,1:2:5]

returns the matrix

2  4  6
3  5  7
4  6  8
5  7  9

where the : in the first slot means all rows and 1:2:5 are the columns 1, 3 and 5.

If we want the first 2 rows and then shuffle the 2,3 and 5th columns in the order 5,3,2 type

A[1:2,[5,3,2]]

to get

6  4  3
7  5  4

. There is a bunch of different ways to return submatrices. See indexing in Julia matrices documentation for more information.

Common Operations on Matrices

There are a number of operations on matrices. For each + and - adds and subtracts two elements (element by element). For example if

A=[1 2 3; 4 5 6]

and

B=[1 3 5; 2 4 6]

then A+B returns the matrix:

$$\left[\begin{array}{ccc} 2 & 5 & 8 \newline 6 & 9 & 12 \end{array} \right]$$

and B-A returns
$$\left[\begin{array}{ccc} 0 & 1 & 2 \newline -2 & -1 & 0 \end{array} \right]$$

The matrix product does not exist between A and B, and if you try A*B, you get:

DimensionMismatch("matrix A has dimensions (2,3), matrix B has dimensions (2,3)")

because the number of columns of A does not equal the number of rows of B. If you need element-by-element multiplication, then A.*B returns
$$\left[\begin{array}{ccc} 1 & 6 & 15 \newline
8 & 20 & 36 \end{array} \right].$$

If you have
C=[4 3 1; 0 0 4; 4 1 1]

Then A*C returns
$$\left[\begin{array}{ccc} 16 & 6 & 12 \newline
40 & 18 & 30 \end{array} \right].$$

where matrix-matrix multiplication from linear algebra was used.

There is also matrix division in julia which is used to solve linear systems. For example if
y=[16;6]
then C\Y solves the linear system CX=Y for X. It returns the vector
$$ \left[\begin{array}-3.0\newline 5.0\end{array}\right]$$

Element by Element Operations

Many methods exist to simplify a vectorized method that returns the operation applied element by element to the matrix. To do this, most operations have a . variety (we saw this above with the .* operation above) To take the square root of every number in the matrix A, we can enter sqrt.(A) which returns:

1.0  1.41421  1.73205
 2.0  2.23607  2.44949

Exercises

Let A=[1,2; 3,4] and B=[1,-1;-1,1].
1. Explain the results of
* A^2
* A.^2
* A*B
* A.*B

  1. Find the sin of every number in A.

Other Operations on Arrays

There are also other operations on arrays. For example, summing all elements in an array is just the sum functions. For example:

sum(1:10)

returns 55. There are also the min, max and prod functions, with the last one, the product of elements.

prod([1,3,5,7])

and notice that use the prod function can simply get us the double factorial function.

function dfact(n)
    return mod(n,2)==1?prod(1:2:n):prod(2:2:n)
end

Sorting Vectors and matrices

Julia can sort a vector using the sort function. If A=[3,2,1,4,8,6,5], Then

sort(A)

results in [1,2,3,4,5,6,8]

Push, Pop and Splice

We have already seen push! which appends an element to an array. Recall that if A=collect(1:5) then

push!(A,7)

returns A which is now the array [1,2,3,4,5,7]. And multiple values can be pushed.

push!(A,8,9,10,100)

results in the array [1,2,3,4,5,7,8,9,10,100]. If we want to concatenate two arrays, we should use the append! command. For example:

append!([1,2,3],[4,5,6])

returns the array [1,2,3,4,5,6].

Check out the Julia docs on sorting algorithms for more details on how Julia does sorting.

pop!

To get an element off of the end of the array, we can use pop!. If A=collect(1:5), then

pop!(A)

returns 5.

Push, pop and Stacks

A stack is a data structure that acts like a stack of paper. You put things on top of them and remove them from the top. The commands push! and pop! work with arrays to act like a stack.

splice!

The splice! function is a Swiss Army knife for arrays. It can take an array, pull elements out and put elements in.

To remove elements out of the array. If A=collect(1:2:9) then

splice!(A,4)

removes and returns the 4th element which is 7. Also, the array A is the original array without the 7 or [1,3,5,9].

If we let A=collect(1:2:11), then

splice!(A,3:5)

removes and returns the 3rd, 4th and 5th elements of A (or [3,5,7]) and A is now the vector [1,3,11]

Now, as I mentioned, splice! is the swiss army knife, because it doesn’t even more!! (Now, how much would you pay?). We can use it to replace elements into the center of an array.

If A=collect(1:2:11), then

splice!(A,3,4)

replaces the 3rd position with the number 4. Note: the 3rd element is returned. This is 5.

If A=collect(1:2:11), then replacing the 3rd element with [-1,-2,-3] by

splice!(A,3,[-1,-2,-3])

returns [1,3,-1,-2,-3,7,9,11] and again 5 is returned.

To insert a number without removing one, we can also use splice!. If A=collect(1:2:11) and we want to insert [-1,-2,-3] at element 3 and shift the rest down:

splice!(A,3:2,[-1,-2,-3])

returns a 0-length array and A=[1,3,-1,-2,-3,5,7,9,11].

filtering elements

A very handle array method, is filter which takes an array and returns only the elements that satisfy some condition.

If A=collect(1:20), then

filter(n->n%2==0,A)

returns all elements that satisfy that the mod 2 is 0 (or even numbers).

removing duplicates with unique

Another handy function is the unique function that takes an array and returns only the unique elements.

If A=[1,2,3,2,3,4,3,4,5,4,3,2,1] then

unique(A)

returns [1,2,3,4,5]. And if you want to update the given array, use the unique! function instead.