# Creating an empty array
my_array = []
# Creating an empty array with an abstract type
my_array = (Integer)[]
# Creating an empty array with a concrete type (results in fastest operation)
my_array = (Float64)[]
# Array with three elements (here the type will be inferred automatically by Julia)
array1 = [1, 2, 3]
This would be akin to what we would consider a column vector in mathematics. We couls also create a row vector by omitting the commas.
array2 = [1 2 3]
We could transpose array1
, which would make it similar to array array2
. Remember that a transpose action interchanges rows and columns.
# Syntax one
transpose(array1)
# Syntax 2
array1'
# Is the transpose equal to the row array
array1' == array2
But the type of the transposed array is not exactly same. Because the transpose
comes from the LinearAlgebra
module, the type of the array changes. We can use the ===
strict equality operator to test that
typeof(array1')
array1'===array2
If we mix various types of elements in an array, then arrays will take on the type of the element that is more encompassing. In the example below, two values will be of Int64
type, but the last is of Float64
type. The array will return the Float64
type.
array3 = [1, 2, 3.0]
array4 = ["one",pi,42]
for i in array4
println("Type of \'$i\' is $(typeof(i))")
end
We can create arrays with more than just a single row or column of elements. This would be akin to a mathematical matrix. We can even create multidimensional arrays. We achieve this by nesting our square brackets and playing with commas and semicolons.
# Note the omission of commas between the inner nested square brackets
array5 = [[1, 2, 3] [4, 5, 6] [7, 8, 9]]
# If we want to populate the elements along row first, we use semicolons
array6 = [[1 2 3]; [4 5 6]; [7 8 9]]
length()
size()
ndims()
# Checking how many elements we have
length(array6)
# Checking size or dimension
size(array6)
# The number of dimension
a = rand(3,2,2);
a
println(ndims(a))
Repeating values is easily accomplished with the repeat([arrayvalues], number of repititions)
function.
# Repeating the values 1 and 2 along a column
repeat([1, 2], 3)
# ...or each value as a row (note no comma in the array definition)
repeat([1 2],3)
We can use built-in functions to create arrays. These can be used in other ways as we will see later.
The range(start value, end value, number of steps)
can be used as an array.
# The values 0 to 10
range(0, 10, length=11)
To access the actuale values, we use the collect()
function.
array7 = collect(range(0, 10, length=11))
To create a logarithmic range i.e. to create a $10^i$ to $10^𝑓$ collection of 20 values...
# i = 2 and f = 3, Note the space between 10 and .^
array8 = collect(10 .^(range(2, 3, length=20)))
array9 = collect(0:1:5)
array10 = collect(0:2:5)
# Creating an empty array of two rows and three columns
# Using an abstract type to leave the values empty
array11 = Array{Integer}(undef, 2,3)
# Specifying a concrete (numerical) type will add random value
array12 = Array{Int64}(undef,3, 3)
Speical functions like ones()
and zeros()
can be used to create arrays with 1's and 0's respectively. Another function fill()
can be used to fill an array with a pre-determined value.
ones(5)
zeros(4)
ones((2,3))
fill(3.5,(3,2))
fill("Julia",(2,3))
Lastly, in this section, we will take a look at reshaping an array. Given an array of elements, we can simply change its dimensions using the reshape()
function.
# Remember array7
array9
# Reshaping it into an array with 2 rows and 3 columns
reshape(array9, 2, 3)
# Reshaping it into an array with 3 rows and 2 columns
reshape(array9, 3, 2)
When arrays get to larger and larger size, we may want to select only sections of it, based on some rule or rules. In this section we recap some of the ways in which this can be achieved and add some new ones.
The rand()
function returns a random value between 0 and 1. We can also specify values to select from. In the example below we choose integers in the range [10, 20] and create an array with ten rows and five columns.
array13 = rand(10:20, 10, 5)
# Selecting all row values in column 2
array13[:, 2]
# All row values in columns 2 and 5
array13[:, [2, 5]]
# All row values in columns 2, 3, and 4
array13[:, 2:4]
# Values in rows 2, 4, 6, and in columns 1 and 5
array13[[2, 4, 6], [1, 5]]
# Values in row 1 from column 3 to the last column
array13[1, 3:end]
Now we take a look at applying some rules. Note how we use the element-wise logic operator in the form of the dot (note the .>
operator in the code below).
Furthermore, by using the findall()
function we can return the index values.
# Boolean logic (returning only true and false)
array13[:, 1] .> 14
# Returning the index of true values using findall()
findall(array13[:, 1] .> 14)
array13
# Sorting along rows
sort(array13,dims=1)
# Sorting along columns
sort(array13,dims=2)
# Returns the max (the first one in case of more than one) and its index in a tuple
findmax(array13)
findmin(array13)
argmax(array13)
argmin(array13)
Collections of elements in the form of arrays can be made much more useful if we could alter the actual values.
We'll start off by adding elemnts to the end of an existing array. This can be done with the push()!
function. Later, we will add a value at the start of an array using the pushfirst!()
function. We will also look at splice!
and append
functions.
array14 = [1, 2, 3, 4]
# Adding the value 5 at the end of the array
push!(array14, 5)
As usual, the exclamation mark reminds you that this function changes the array.
# Adding the value 0 at the start of the array
pushfirst!(array14, 0)
To insert an element into an array at a given index, use the splice!()
function. For example, here's a list of numbers with an obvious omission:
array14 = [1, 2, 3, 5, 6, 7, 8, 9]
Use splice!()
to insert a sequence at a specific range of index values. Julia returns the values that were replaced. The array grows larger to accommodate the new elements, and elements after the inserted sequence are pushed down. Let's insert, at position 4:5
, the range of numbers 4:6
:
splice!(array14, 4:5, 4:6)
array14
If you don't supply a replacement, you can also use splice!()
to remove elements and move the rest of them along.
splice!(array14,6:8)
array14
To remove the last element use pop!
pop!(array14)
array14
... and to remove the first, popfirst!
popfirst!(array14)
array14
The function append!
can be used to push a second collection at the back of the first one
a1 = collect(1:5);
a2 = collect(101:105);
append!(a1,a2)
# Create an array with elements 3.x^2 where x is an odd number between 1 and 9 (inclusive)
array15 = [3*i^2 for i in 1:2:9]
# Can use multiple variables for the initialization of 2D array
array16 = [a+2b for a in -1:1, b in -2:2]
# Array of squared elements if the square is not divisible by 5 or 4 (note that we need to use &&)
array17=[i^2 for i=1:10 if (i^2%5!=0 && i^2%4!=0)]
sum
prod
mean
std
middle
median
array17
sum(array17)
prod(array17)
Functions like mean()
, std()
and middle()
have been moved into the Statistics
module in the standard library; you may need to first enter "using Statistics"
to use them
using Statistics
mean(array17)
std(array17)
middle(array17)
median(array17)
For 2D arrays, we can specify dimensions (axis) along which the summary operation is to be performed
array16
std(array16)
mean(array16,dims=1)
mean(array16,dims=2)
array18 = [2*a+b for a in 1:3, b in -2:2]
array16
array16+array18
# Note the DOT in fron of the * to denote element-wise operation
array16.*array18
# Division can produce `Inf` values if divided by zero
array18./array16
We can even raise one array to the power of another array element-wise. But for this to work, at least one of them has to be a Float
type, not Integer
. So, we create a Float64
array and demonstrate this.
array19 = (Float64)[a+b for a in 1:3, b in -1:3]
array18.^array19