Quiz 1.5: Arrays
Q1: How to write arrays
Given the following snippet:
a = XXX
b = fill(3,2)
c = a .* b
and knowing that c[1][1]
is equal to 3',
c[1][2]is equal to
6and
c[2]is equal to
9(i.e.
c = [[3,6],9]), which is the value of
a, i.e.
XXX` in the script ?
(your answer should start and end with a square bracket and include no spaces)
RESOLUTION
c
is made by multiplicating each element of a
with the vector [3,3]
. From the question we know that the first element is a vector itself of two integers, 3
and 6
, and the second element is an integer, 9
(hence a scalar). So a
is just a vector with the same structure but the individual elements divided by 3
.
The correct answer is: "[[1,2],3]"
Q2: Array theory
Which of the following sentences are correct?
RESOLUTION
A few notes concerning the wrong sentences: Linear albebra functionality is included directly in the standard library, no need for a third party package at all; The size on different dimensions can be different (e.g. rand(2,3,4)
produces a 3-dimensional array whose size is (2,3,4)
); Arrays can contain heterogeneous elements (at the cost of reduced performances); Being "column mayor" means that arrays are "physically" stored in memory by columns. Accessing one of this elements consequentiality, one after the other, is cheap. This means that it is cheaper to loop over the various rows of the same columns than looping over the various column of the same row and hence better to keep the loop over the rows as the inner loop; The transpose
function works only with numerical matrices. Use permutedims
instead for non-numerical matrices.
The correct answers are:
- "For multidimensional arrays the number of elements on any given dimension must be the same"
- "When the algorithm allows to know the number of elements in an array, it is often more efficient to first create and allocate memory for the array and then modify each individual element compared to start with an empty array and then add the individual elements"
Q3: Initialisation of arrays
Which of the following are valid methods to create a 2 columns, 3 rows matrix ?
RESOLUTION
Note that we are looking for a 3x2 matrix, not a 2x3 one.
The correct answers are:
- "
rand(3,2)
" - "
[x + y for x in 40:10:60, y in 2:3]
" - "
rand(1:5,3,2)
" - "
[1 2;3 4;5 6]
"
Q4: Basic Linear Algebra
Given the following snippet:
a = [1 2 3; 4 5 6]
b = a[:,2]' * a[?₁,?₂:3]
and knowing that (1) b
is equal to 19
and (2) ?₁
and ?₂
are two numbers, which is the sum of ?₁ + ?₂
?
RESOLUTION
The output (b
) is a scalar, and the multiplier is a (1x2) vector, so the multiplicand must be a (2x1) vector. This tells already that ?₂
must be 2
. Now, ?₁
could be one, so that the multiplicand is a[1,2:3] = [2,3]
or two, so that a[2,2:3] = [5,6]
. Knowing that the results of the inner product is 19
we resolve for the first option.
The correct answer is: 3