0% found this document useful (0 votes)
0 views

Week_2_Part_1_Arrays_and_Matrices

The document provides an introduction to arrays and matrices in MATLAB, covering their definitions, creation, and indexing. It explains the importance of MATLAB for matrix operations and includes practical examples for creating and manipulating arrays. Additionally, it highlights the use of built-in functions for efficient vector creation and demonstrates how to index and modify elements within matrices.

Uploaded by

Ngọc Vi Cao
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views

Week_2_Part_1_Arrays_and_Matrices

The document provides an introduction to arrays and matrices in MATLAB, covering their definitions, creation, and indexing. It explains the importance of MATLAB for matrix operations and includes practical examples for creating and manipulating arrays. Additionally, it highlights the use of built-in functions for efficient vector creation and demonstrates how to index and modify elements within matrices.

Uploaded by

Ngọc Vi Cao
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 43

Arrays and Matrices

Where do I find MATLAB? Here!

Do I have to have MATLAB installed on my computer right


now? No, you can use MATLAB Online!

© 2023 Introduction to Programming in MATLAB (2), Arrays and Matrices 1


Table of Contents
Recap of Week 1: Introduction and Data Types
Arrays and Matrices
Introduction to arrays and matrices
Array creation
Array Indexing
Array concatenation
Operate with functions on arrays
What we've covered this week in part 1: Arrays and Matrices
Extra resources
References
MATLAB Live Script

© 2023 Introduction to Programming in MATLAB (2), Arrays and Matrices 2


Recap of Week 1:
Introduction and Data Types
Last week, we learnt about:
 What programming is
 What MATLAB is
 Data types
 Variables and Commands
 Mathematical Functions
 MATLAB Live Editor
This week we have split the content into two parts. We begin with Part 1: Arrays
and Matrices, which covers the following:
 What arrays and matrices are
 Creating arrays
 Indexing into arrays
 Concatenation of arrays
 Operating with function on arrays
© 2023 Introduction to Programming in MATLAB (2), Arrays and Matrices 3
Arrays and Matrices
Introduction to arrays and matrices

The name MATLAB is an abbreviation of "MATrix LABoratory". MATLAB was designed to


work with matrices as the fundamental unit of data.

© 2023 Introduction to Programming in MATLAB (2), Arrays and Matrices 4


Arrays and Matrices
A matrix is regular two-dimensional grid, or table, of numbers, with rows and/or columns.

© 2023 Introduction to Programming in MATLAB (2), Arrays and Matrices 5


Arrays and Matrices
They can come in many shapes and sizes, and we have a special case when there is
only a single row and/or column.

© 2023 Introduction to Programming in MATLAB (2), Arrays and Matrices 6


Arrays and Matrices
Let us consider what MATLAB understands arrays and matrices to be. Refer to the image
below, beginning at the smallest, inner most oval and working our way to the largest,
outer most oval. When there is only one row and one column, we have a scalar value. A
scalar value would be any numerical value that includes the digits 0 to 9, in a positive or
negative form, for example 5 or-5.

© 2023 Introduction to Programming in MATLAB (2), Arrays and Matrices 7


Arrays and Matrices
When there is a single row or column, we have a vector. A vector is a collection of scalar
values/elements arranged in row or column form and is also known as a 1-D numeric
array. Combining row or column vectors results in a matrix, which is also referred to as a
2-D numeric array. When you wish to include data that is not in numeric form, we refer to
the variable simply as an array. An array can have multiple data types and values in one
variable and can be of any size/dimension. Examples of arrays include:

• Numeric arrays
• Character arrays
• Cell arrays
• Tables

© 2023 Introduction to Programming in MATLAB (2), Arrays and Matrices 8


Arrays and Matrices
You interact with applications of matrices and arrays in your everyday life, with images
being likely the most common one. An image is stored in electronic devices as arrays or
matrices, where each pixel in the image is represented by a single element in an 2-
dimensional array or matrix. For grayscale images, only one matrix is stored with element
values between 0 (white) and 1 (black). Colour images are a collection of three
array/matrix layers based on RGB code, i.e. a matrix for Red, Green, and Blue coded
numerical values.

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)

© 2023 Introduction to Programming in MATLAB (2), Arrays and Matrices 9


Arrays and Matrices

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.

© 2023 Introduction to Programming in MATLAB (2), Arrays and Matrices 10


Array creation
Creating vectors by specifying each element individually

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

Note: MATLAB interprets a comma as a separator and not a decimal point.


© 2023 Introduction to Programming in MATLAB (2), Arrays and Matrices 11
Array creation
To create a column vector, simply use a semi-colon to separate the values:

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

a_4 = [1; 2; 3; 4]’


a_4 = 1×4

1 2 3 4

© 2023 Introduction to Programming in MATLAB (2), Arrays and Matrices 12


Array creation
Now you try! Create a row vector called x_1 with the values 2, 4, 6, and 8.

x_1 = [2, 4, 6, 8]
x_1 = 1×4
2 4 6 8

© 2023 Introduction to Programming in MATLAB (2), Arrays and Matrices 13


Array creation
Creating vectors of equally spaced element values

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.

Method 1: Using the notation var = start : step size : end


a_5 = 1:2:10
a_5 = 1×5
1 3 5 7 9

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.

© 2023 Introduction to Programming in MATLAB (2), Arrays and Matrices 14


Array creation
Creating vectors of equally spaced element values

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 ⋯

© 2023 Introduction to Programming in MATLAB (2), Arrays and Matrices 15


Array creation
Creating vectors of equally spaced element values

Method 2: Using the built in function var = linspace(start, end, number of


elements)
a_8 = linspace(1,10,5)
a_8 = 1×5
1.0000 3.2500 5.5000 7.7500 10.0000

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.

© 2023 Introduction to Programming in MATLAB (2), Arrays and Matrices 16


Array creation
Creating vectors of equally spaced element values
Now you try! Create a row vector x_4 that spans from 0 to 10 with 100 elements
equally spaced.

x_4 = linspace(0,10)


x_4 = 1×100
0 0.1010 0.2020 0.3030 0.4040 0.5051 0.6061

© 2023 Introduction to Programming in MATLAB (2), Arrays and Matrices 17


Array creation
Creating vectors using other built-in functions

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

© 2023 Introduction to Programming in MATLAB (2), Arrays and Matrices 18


Array creation
Next, let us create a vector or values drawn from a uniform distribution in the interval (0,
1). The function rand is used to do this, following the same notation as the functions
ones and zeros, var = rand(r, c)
b_3 = rand(1,5)

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 ⋯

© 2023 Introduction to Programming in MATLAB (2), Arrays and Matrices 19


Array Indexing
In this subsection, we will cover how to index into arrays to extract or reassign one or
more elements. We begin by initialising an arbitrary variable matrix, A:
syms a11 a12 a13 a21 a22 a23 a31 a32 a33

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 =[a11 a12 a13; a21 a22 a23; a31 a32 a33]

A =

To index into a matrix, specify the row, r, and column, c, numbers of interest using the
notation MatrixName(r, c).

© 2023 Introduction to Programming in MATLAB (2), Arrays and Matrices 20


Array Indexing
Let us access the element in the first row and the second column of the above matrix, A
and assign it to a new workspace variable.
NewWorkspaceVariable_1 = A(1,2)

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 =

In a similar way, let us extract all rows of the second column:

NewWorkspaceVariable_3 = A(:,2)

NewWorkspaceVariable_3 =

© 2023 Introduction to Programming in MATLAB (2), Arrays and Matrices 21


Array Indexing
When referencing rows or columns, MATLAB interprets a colon as all the rows or
columns (as seen above). Sometimes only specific elements of the array are required, so
being able to specify this in a single command is useful. MATLAB allows referencing
elements in an array by specifying the indices/positions in an array, for example let us
extract the elements from column 2 until the last column, of row 1 in matrix A:

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.

© 2023 Introduction to Programming in MATLAB (2), Arrays and Matrices 22


Array Indexing
So far, we have covered how to reference from an array to create a new workspace
variable. Now, we will consider how to replace/overwrite an element in an array. As we
references a row and column above when extracting the element value, we now use
assignment to that element value, i.e. the matrix reference will be on the left-hand side of
the equals sign MatrixName(r, c) = value. Let us replace the element in column 3
of the first row with the value 10:

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.

© 2023 Introduction to Programming in MATLAB (2), Arrays and Matrices 23


Array Indexing
The assignment operation to an array row or column can also be used to remove/delete
the row or column respectively, by assigning the entire row or column to an empty array
[]. As an example, let us remove the entire first row of the matrix A:

A(1,:) = []

A =

© 2023 Introduction to Programming in MATLAB (2), Arrays and Matrices 24


Array Indexing
Now you try! Create a 3-by-3 symbolic matrix A as demonstrated in the beginning of
the Array indexing section.
syms a11 a12 a13 a21 a22 a23 a31 a32 a33
A =[a11 a12 a13; a21 a22 a23; a31 a32 a33];

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 =

© 2023 Introduction to Programming in MATLAB (2), Arrays and Matrices 26


Array concatenation
Array concatenation is the process of combining two or more arrays into a single array.
There are two ways of concatenating arrays; horizontally and vertically, both of which use
the notation you learnt in the Creating vectors by specifying each element individually
subsection.

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.

© 2023 Introduction to Programming in MATLAB (2), Arrays and Matrices 27


Array concatenation
Let us try this operation by horizontally concatenating a 2-by-2 matrix A with a 2-by-1
matrix (column vector) x:

syms a11 a12 a21 a22 x1 x2

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 =[a11 a12; a21 a22]

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 =[a11 a12; a21 a22]

A =

x = [x1; x2]

x =

A = [A; x]

A =

© 2023 Introduction to Programming in MATLAB (2), Arrays and Matrices 29


Array concatenation
Horizontal and vertical concatenation can also be combined in a single operation as long
as the dimensions match, i.e. the number of rows and columns are equal when
concatenating vertically and horizontally respectively. For example, consider 3 matrices,
A, B, and C which have the dimensions 4-by-4, 1-by-4, and 5-by-2 respectively.
What command will combine all three matrices into a single matrix with dimensions 6-
by-6?

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.

© 2023 Introduction to Programming in MATLAB (2), Arrays and Matrices 30


Array concatenation
Let us begin by defining the three matrices:

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];

© 2023 Introduction to Programming in MATLAB (2), Arrays and Matrices 31


Array concatenation
As described above, concatenate matrix A and B vertically ([A; B]) and then
horizontally concatenate that resulting matrix with matrix C (NewMatrix = [[A; B]
C]):

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

© 2023 Introduction to Programming in MATLAB (2), Arrays and Matrices 32


Operate with functions on arrays
Many built in functions of MATLAB can be applied directly to arrays, eliminating the need
for iterating through each element of an array. In this subsection we will consider basic,
element-wise arithmetic, and then operate on an array with three (of many) mathematical
functions.

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.

© 2023 Introduction to Programming in MATLAB (2), Arrays and Matrices 33


Operate with functions on arrays
To get us started, let us define 2 vector arrays a and b with 5 equally spaced element
values as follows:

a = 10:10:50
a = 1×5
10 20 30 40 50

b = 5:-1:1
b = 1×5
5 4 3 2 1

© 2023 Introduction to Programming in MATLAB (2), Arrays and Matrices 34


Operate with functions on arrays
Let us consider the element-wise multiplication and division of the vector arrays a and b,
denoted respectively by the operators .* and ./

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.

© 2023 Introduction to Programming in MATLAB (2), Arrays and Matrices 35


Operate with functions on arrays
Now you try! Consider the following 2 vector arrays, quantity,
price_per_pack, which represent the number of pears in a fruit pack, and its
corresponding selling price in ZAR per fruit pack, respectively.

quantity = 2:2:8;

price_per_pack = [10 18 25.5 30];

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

5.000000000000000 4.500000000000000 4.250000000000000 ⋯

© 2023 Introduction to Programming in MATLAB (2), Arrays and Matrices 36


Operate with functions on arrays
There are many operators that can be applied directly to arrays, including trigonometric,
logarithmic, and other mathematical functions. Let us demonstrate this by first creating an
array of values in the interval [0, 2π], and then operating on the array with the sin, tan,
and log functions.

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.

© 2023 Introduction to Programming in MATLAB (2), Arrays and Matrices 38


Operate with functions on arrays
Next, let us create a vector or values drawn from a uniform distribution in the interval
(0, 1). The function rand is used to do this, following the same notation as the
functions ones and zeros, var = rand(r, c)
b_3 = rand(1,5)
b_3 = 1×5
0.8147 0.9058 0.1270 0.9134 0.6324

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

© 2023 Introduction to Programming in MATLAB (2), Arrays and Matrices 39


What we've covered this week in part 1:
Arrays and Matrices
This week in part 1, we learnt about:

 What arrays and matrices are


 Creating arrays
 Indexing into arrays
 Concatenation of arrays
 Operating with function on arrays

In the next part of this week's content, we will be learning about relational and logical
operators, covering the following sub-topics:

 Introduction to decision making with operators


 Relational operators
 Logical operators

© 2023 Introduction to Programming in MATLAB (2), Arrays and Matrices 40


Extra resources
 Documentation: MATLAB Fundamentals
 Video: How to Make a Vector in MATLAB
 Video: How to Insert Data Into a Vector in MATLAB
 Documentation: Removing Rows or Columns from a Matrix
 Video: Working with Arrays in MATLAB
 Video: Indexing Columns and Rows
 Documentation: Matrices and Arrays - Functions
 MATLAB Fundamentals Self-paced Course
 Self-Paced Online Courses

© 2023 Introduction to Programming in MATLAB (2), Arrays and Matrices 41


References
 Documentation: MATLAB Fundamentals
 Image Compression with Low-Rank SVD

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

© 2023 Introduction to Programming in MATLAB (1), Fundamentals 43

You might also like