Week_2_Part_1_Arrays_and_Matrices
Week_2_Part_1_Arrays_and_Matrices
• Numeric arrays
• Character arrays
• Cell arrays
• Tables
Now you try! Run the following code will import a stock image from MATLAB, convert
it to grayscale, and display it.
A = imread('street1.jpg’);
B = rgb2gray(A);
imshow(B)
Take a look in the workspace at the variables created in the code above. You'll notice that
A is an array with three matrices (one for each RGB layer) with 480 rows and 640
columns each, and B is a matrix with 480 rows and 640 columns. The number of pixels
in an image is determined by taking the number of rows and multiplying it by the number
of columns, i.e. for this image there are 307 200 pixels.
We use square brackets, [], in MATLAB to denote numeric arrays. There are a few
ways of creating an array in MATLAB. As MATLAB's convention defines observations as
rows and columns as variables of the observations, let us begin by creating some row
vectors. To separate values in a row vector you can either use a space or a comma:
a_1 = [1 2 3 4]
a_1 = 1×4
1 2 3 4
a_2 = [1, 2, 3, 4]
a_2 = 1×4
1 2 3 4
a_3 = [1; 2; 3; 4]
a_3 = 4×1
1
2
3
4
You can interchange between row and column vectors by transposing between one and
the other. This is done by including an inverted comma after the closing square bracket,
for example
1 2 3 4
x_1 = [2, 4, 6, 8]
x_1 = 1×4
2 4 6 8
Typing out each element of a vector can be tedious and time consuming. In the case
where you require a vector to be created with equally spaced element values, there are
two approaches available.
a_6 = 10:-2:1
a_6 = 1×5
10 8 6 4 2
We use the colon operator to create regularly spaced vectors, index into arrays, and
define the bounds of a for loop. For now, we are considering its application in vector
creation, but we will get to its other applications later on.
You will notice that the specified "end" value is not necessarily the last element's value
when using this approach, as with the output for variable a_6. This is a distinct
difference between this approach and the following one. Another important property of
this approach is that if you do not specify the "step size" in this notation, MATLAB will
assume you are requesting for a step size of 1.
a_7 = 1:4
a_7 = 1×4
1 2 3 4
Now you try! Create a row vector x_3 that spans from to equally spaced of 0.2
x_3 = -2*pi:0,2:2*pi
x_3 = 1×63
-6.2832 -6.0832 -5.8832 -5.6832 -5.4832 -5.2832 -5.0832 ⋯
This approach gives the user direct control of the number of points/elements and ensures
that the last element of the vector is the value specified by the user. MATLAB
automatically calculates what step size is required given the user's input to the function. It
is important to note that if the number of points/elements is not specified by the user,
MATLAB will assume a default value of 100 points is required.
x_4 = linspace(0,10)
⋯
x_4 = 1×100
0 0.1010 0.2020 0.3030 0.4040 0.5051 0.6061
There are a few built in functions you can leverage for creating vectors and matrices in
MATLAB. This subsection will cover 3 examples of such functions, which will come in
handy when trying to avoid computationally expensive iterative scripts/loops. Let us begin
by creating a vector with all elements being the value 1, and then a second vector where
all elements have a value of 0. Both of these functions expect two inputs, one for the
number of rows, r, and the next for the number of columns, c, i.e. var = ones(r, c)
or var = zeros(r, c)
b_1 = ones(1,5)
b_1 = 1×5
1 1 1 1 1
b_2 = zeros(1,5)
b_2 = 1×5
0 0 0 0 0
b_3 = 1×5
0.8147 0.9058 0.1270 0.9134 0.6324
Now you try! Create a row vector x_5 that spans from 0 to 10 with 100 elements
equally spaced.
x_5 = linspace(0,10)
x_5 = 1×100
0 0.1010101010101010 0.2020202020202020 ⋯
Aside: You can look up the Symbolic Math Toolbox for more details on the above
command however, this will be covered in a future section of this course.
A =
To index into a matrix, specify the row, r, and column, c, numbers of interest using the
notation MatrixName(r, c).
NewWorkspaceVariable_1 =
To extract an entire row or column, use a colon, :, instead of specifying the column or
row number, for example let us extract the all the columns of row 1:
NewWorkspaceVariable_2 = A(1,:)
NewWorkspaceVariable_2 =
NewWorkspaceVariable_3 = A(:,2)
NewWorkspaceVariable_3 =
NewWorkspaceVariable_4 = A(1,2:end)
NewWorkspaceVariable_4 =
You'll notice that instead of specifying the end index value, 3, the syntax end was used.
This is a convenient way to index the last element in an array without first determining its
value, and this approach to coding assists with code readability.
A(1,3)=10
A =
Note:The element has now been replaced by the value 10. This operation cannot be
undone, and the only way to have a value in column 3 of the first row, is to reassign that
variable to the element position.
A(1,:) = []
A =
Extract the element from the third column and second row, and assign it to the variable
x_6.
x_6 = A(2, 3)
x_6 =
Extract the entire third row, and assign it to the variable x_7.
x_7 = A(3, :)
x_7 =
© 2023 Introduction to Programming in MATLAB (2), Arrays and Matrices 25
Array Indexing
Replace the element in third row and second column with the value 5.
A(3, 2) = 5
A =
To concatenate horizontally, simply use the square bracket (and comma) notation used
when combining elements into a row vector, i.e. NewMatrix = [Matrix_1
Matrix_2] or NewMatrix = [Matrix_1, Matrix_2]. It is important that the
number of columns is the same for all the arrays being concatenated.
Aside: You can look up the Symbolic Math Toolbox for more details on the above
command however, this will be covered in a future section of this course.
A =
x = [x1; x2]
x =
A = [A x]
A =
The above is the result of horizontally combining the matrix A with the column vector x.
© 2023 Introduction to Programming in MATLAB (2), Arrays and Matrices 28
Array concatenation
To concatenate vertically, simply use the square bracket and semicolon notation used
when combining elements into a column vector, i.e. NewMatrix = [Matrix_1;
Matrix_2]. It is important that the number of rows is the same for all the arrays being
concatenated. Let us try this operation by vertically concatenating a 2-by-2 matrix A with
a 1-by-2 matrix (row vector) x:
A =
x = [x1; x2]
x =
A = [A; x]
A =
The above image illustrates graphically how this operation should take place. There is a
vertical concatenation of A and B, and then a horizontal concatenation of the result with
matrix C.
syms a11 a12 a13 a14 a21 a22 a23 a24 a31 a32 a33 a34 a41 a42 a43 a44
b11 b12 b13 b14 c11 c12 c21 c22 c31 c32 c41 c42 c51 c52
A = [a11 a12 a13 a14;
a21 a22 a23 a24;
a31 a32 a33 a34;
a41 a42 a43 a44];
B = [b11 b12 b13 b14];
C = [c11 c12;
c21 c22;
c31 c32;
c41 c42;
c51 c52];
NewMatrix = [[A; B] C]
NewMatrix =
Now you try! Create a matrix array, A, with element values 1, 2, 4, and 5, and
a column vector array, b, with element values 3, and 6. Horizontally concatenate the
vector array to the right-hand side of the matrix array.
A =[1 2; 4 5];
b = [3; 6];
[A, b]
ans = 2×3
1 2 3 4 5 6
At this point in your academic year, you have likely covered some linear algebra
operations, including matrix multiplication and "division" (using the transpose of a matrix).
These are different operations from element-wise multiplication and division, in that they
operate on the whole row or column of the array and not just a single element position at
a time. See documentation on mtimes and mrdivide for more information on these matrix
operations. Let us now demonstrate some basic, element-wise arithmetic.
a = 10:10:50
a = 1×5
10 20 30 40 50
b = 5:-1:1
b = 1×5
5 4 3 2 1
a.*b
ans = 1×5
50 80 90 80 50
a./b
ans = 1×5
2 5 10 20 50
Note that the vector arrays, a and b, have the same dimensions, and the output has the
same dimensions as the input arrays. Consult the documentation for times and
rdivide for more information about their other operating properties.
quantity = 2:2:8;
Determine the selling price per unit (pear) when a fruit pack is chosen, i.e. use element-
wise division of price_per_pack by quantity.
price_per_pack./quantity
ans = 1×4
x = linspace(0,2*pi)
x = 1×100
0 0.0635 0.1269 0.1904 0.2539 0.3173 0.3808 ⋯
y_1 = sin(x)
y_1 = 1×100
0 0.0634 0.1266 0.1893 0.2511 0.3120 0.3717 ⋯
y_2 = tan(x)
y_2 = 1×100
0 0.0636 0.1276 0.1927 0.2595 0.3284 0.4003 ⋯
y_3 = log(x)
y_3 = 1×100
-Inf -2.7572 -2.0641 -1.6586 -1.3709 -1.1478 -0.9655 ⋯
© 2023 Introduction to Programming in MATLAB (2), Arrays and Matrices 37
Operate with functions on arrays
Note that all 100 evaluated values of each function were generated with a single line of
code. If you are unsure of whether a function can operate on an array, search for its
definition in the documentation either by:
• Using the Search Documentation box on the top right-hand corner of the
MATLAB user interface
• Typing the function in a code section or the command window and press
F1 or right-click and select Help on "Function“
If the function does not operate on an array, make use of the arrayfun function. See
arrayfun documentation for more on this.
Now you try! Create a row vector array, x, with 5 equally spaced element values
between -1 and 1. Determine the absolute value of this array using the abs function.
x = linspace(-1,1,5)
x = 1×5
-1.0000 -0.5000 0 0.5000 1.0000
abs(x)
x = 1×5
1.0000 0.5000 0 0.5000 1.0000
In the next part of this week's content, we will be learning about relational and logical
operators, covering the following sub-topics:
Copyright 2022 The MathWorks, Inc. & Opti-Num Solutions (Pty) Ltd.
© 2023 Introduction to Programming in MATLAB (2), Arrays and Matrices 42
MATLAB Live Script
Click on the link below for this lecture’s MATLAB live Script
• Week_2_Part_1_Arrays_and_Matrices.mlx