0% found this document useful (0 votes)
19 views172 pages

Matlab Tutorials

The document outlines a MATLAB course taught by Vincent Mwai, covering topics from basic to advanced skills. It includes sections on the graphical user interface, common operations, handling variables, basic mathematics, and operations on matrices. Each section contains learning objectives and detailed explanations of various MATLAB functions and commands.

Uploaded by

markmuriithi89
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views172 pages

Matlab Tutorials

The document outlines a MATLAB course taught by Vincent Mwai, covering topics from basic to advanced skills. It includes sections on the graphical user interface, common operations, handling variables, basic mathematics, and operations on matrices. Each section contains learning objectives and detailed explanations of various MATLAB functions and commands.

Uploaded by

markmuriithi89
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 172

MATLAB COURSE

Lecturer:

Vincent Mwai
Contents

I Matlab Skills Basic to Advance 9

1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11

2 Graphical User Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13


2.1 Learning Objectives 13
2.2 Graphical User Interface 13
2.2.1 The Command Window . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
2.2.2 The Current Folder . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
2.2.3 The Workspace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16

3 Some Common Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17


3.1 Learning Objectives 17
3.2 Some Common Operations 17
3.2.1 whos command . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
3.2.2 clear command . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
3.2.3 Others . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19

4 Handling Variables and Creating Scripts . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21


4.1 Understanding Variables 21
4.1.1 Learning Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
4.2 Different Types of Variables 23
4.2.1 Learning Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
4.2.2 Characters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
4.2.3 String . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
4.2.4 Logical . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
4.3 Creating Scripts and Understanding Commenting and Semicolon effect 27
4.3.1 Learning Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
4.4 Colon and Its Usage 30
4.4.1 Learning Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30

5 Basic Mathematics in MatLab . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33


5.1 Addition, Multiplication, subtraction and powers 33
5.1.1 Learning Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
5.2 Computing GCD, LCM, Permutations and Prime Numbers 36
5.2.1 Learning Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
5.3 Trigonometric Functions 40
5.3.1 Learning Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
5.4 Set Operations 46
5.4.1 Learning Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
5.5 Computing Statistics of the Matrices 50
5.5.1 Statistical Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
5.6 Random Numbers 55
5.6.1 Learning Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55
5.7 Cross and Dot Product 59
5.7.1 Learning Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
5.7.2 The Dot Product . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
5.7.3 The Cross Product . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61
5.8 Logic Operations 62
5.8.1 The and operator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62
5.8.2 The or operator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63
5.8.3 The not operator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64
5.9 Sign and Absolute Functions 64
5.9.1 The sign functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
5.9.2 The abs function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
5.10 Number Conversions 67
5.10.1 The dec2base Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
5.10.2 The base2dec function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
5.11 Discretizing your Data 68
5.12 Practice Exercise Questions 71

6 Operations on Matrices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73
6.1 Computing Unique Elements 73
6.2 Membership and Equality 76
6.2.1 The ismember function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76
6.2.2 The isequal function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78
6.3 Shifting Matrix Elements 79
6.3.1 Shifting Matrix Elements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79
6.4 Matrix Operations 81
6.4.1 Inverse of a matrix . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
6.4.2 Determinant of a matrix . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82
6.4.3 Diagonal Elements of a Matrix . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82
6.5 Relational Operations 84
6.5.1 Greater than or equal to . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84
6.5.2 Greater than . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85
6.5.3 The Less Than . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86
6.5.4 The Less Than or equal to . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87
6.5.5 The Not Equals To operation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88
6.6 Common Matrices 90
6.6.1 The Matrix of Ones . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90
6.6.2 The Matrix of zeros . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90
6.7 Sorting Matrix Values 91
6.7.1 Sorting Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91
6.8 Size and Length Functions 94
6.9 The size function 95
6.10 The length function 95
6.11 Matrix Concatenation 97
6.11.1 Matrices Row Concatenation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97
6.11.2 Matrices Columns Concatenation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97
6.12 Finding Non-Zero Elements 98
6.13 Frequency of Values within a Vector 100
6.14 Practice Exercise 103
6.15 Practice Exercise Advanced 103

7 Math Functions with Symbolic Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . 105


7.1 Symbolic Variables 105
7.2 Differentiation and integration 106
7.2.1 Differentiation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107
7.2.2 Higher Order Differentiation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 108
7.2.3 Integration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109
7.3 Solving Equations 110
7.4 Symbolic Functions 113

8 Interacting with MatLab Graphics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115


8.1 Basic Input Output 115
8.2 More Input Output Commands 116
8.3 Plotting Data 118
8.4 3D Plots 120
8.5 More on Plotting Options 121
8.6 Bar Graphs 125
8.7 Combining Plots 129
8.8 Brush Tool for Plots 130
8.9 Plots with two Y-Axis 131
8.10 Animated Line 132
8.11 Existence of Scripts, files, folders, etc 133
8.12 Directory Manipulation 134
8.13 Textual Processing 138
8.14 Project Exercise 1 140

9 Importing Data into MatLab . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143


9.1 Importing data from Excel 143
9.2 Importing data in Different Formats 144
9.3 Practice Exercise 146

10 MatLab Programming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151


10.1 Conditional If Statement 151
10.2 Continue Statement 152
10.3 For Loops 153
10.4 Nested For Loops 154
10.5 While Loops 155
10.6 Break Statement 155
10.7 Switch Statement 156
10.8 Pracitce Exercise 4 157

11 Creating Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 159


11.1 Functions 159
11.2 Functions with Inputs 159
11.3 Functions with Inputs and Outputs 160
11.4 Return Statement 161

12 Sharing MatLab Results . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 163


12.1 Sharing Results 163

13 Solutions to Practice Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 167


13.1 Solutions to Practice Exercise 5.12 167
13.2 Solution to Practice Exercise 6.14 167
13.3 Solution to Practice Exercise 6.15 168
13.4 Solution to Project Exercise 1 169
13.5 Solution to Practice Exercise 9.3 169
13.6 Solutions to practice exercise 10.8 170
Part I

Matlab Skills Basic to Advance


1. Introduction
2. Graphical User Interface

2.1 Learning Objectives

Introduction to key Graphical user interface componets of Matlab

• Command window
• Workspace
• Current folder
• Various tabs

2.2 Graphical User Interface

In this section we are going to look at the key graphical interface components of the MATLAB software.

The first component we are going to explain is the command window

2.2.1 The Command Window

This is the place where we interact with the MatLab software. By interaction, we mean that we are going
to provide useful inputs to the MatLab here and then we can expect certain results out of the computation
of manipulating those inputs.
14 Chapter 2. Graphical User Interface

A MatLab Command Window

In the command window, we can perform some operations, for instance, addition, Subtraction,
multiplication, division, integration and so on

Some operations on the command Window

In conclusion, you may consider it as part of base calculator. But MatLab goes beyond that and can
perform more sophisticated and more complicated operations.

2.2.2 The Current Folder


This is the folder or directory location where our current scripts and MatLab files are located and these
files can be executed on the matlab software.
2.2 Graphical User Interface 15

The Current Folder

This particular bar shows the directory location of the folder which is called the current folder.

Current Folder Path

If you want to change the current folder, just click the fourth icon ,from left, bar and a file chooser
will pop up and select the folder you want to open.

Changing The Current Folder

Whenever you want to write certain scripts, you should make sure that you are in the correct current
folder.
On the top part of the MatLab GUI, we have some buttons such as New Script,New,Open etc. As we
progress with the course, these buttons will become more relevant.
On the second tab pane, we have plots. In this pane, there contains different plotting options.

Plots Pane

On the third tab pane, there are some useful apps that people have contributed.
16 Chapter 2. Graphical User Interface

Apps on Matlab

2.2.3 The Workspace


This component will become more clear as we progress with the course. But for now, just know that it is
a component that will keep track of all our variables that are currently being processed by the MatLab
software. In a case where we do not declare a variable name, the output is stored in a default kind of a
variable which is called ans

In the Workspace, it contains the name of the variable, the value of the variable and the size of the
variable. In MatLab, data is stored as arrays.
3. Some Common Operations

3.1 Learning Objectives


Learning some common operations
• How to clear command Window
• Look at current variables
• Delete current variables
• Basics of variables

3.2 Some Common Operations


In the previous section, we saw that we could perform certain basic math operations. In order to store the
results of some mathematical complicated operations we can use the concept of what we call variables. .
A variable is a data container which can store the results of mathematical operations.
We can define a variable that starts from a letter and then we can assign it any value. For instance, if
we say

a = 16

, a now will contain a value of 16 and can be seen in the workspace

We can also define variables which contains the result of mathematical operations, the result is first
computed and then the result is stored in the variable

a = 123 + 3 − 18
18 Chapter 3. Some Common Operations

We also note that whenever we assign a new value to an already existing variable, the previous value
it was holding is replaced with the current value. In our case, we note that a is overwrite and now contains
1713
If you want to retain all the variables, then it is advisable to have variables with different variable
names. Such as, in our example above, we could say b = a, then b would have a copy of the value of a
which was 16, then continue assigning a new result to the variable a. In this case we will have both results
in different variables.

Whenever we change the value of a, b will still have the copy of value of a at the time of assignment.

3.2.1 whos command


whos List current variables, long form. whos is a long form of WHO. It lists all the variables in the current
workspace, together with information about their size, bytes, class, etc.
In a nested function, variables are grouped into those in the nested function and those in each of the
containing functions, each group separated by a line of dashes.
3.2 Some Common Operations 19

3.2.2 clear command


The clear command can be used to delete some variables and functions that are no longer needed to free
up space and memory. clear Clear variables and functions from memory.
clear removes all variables from the workspace.
clear VARIABLES does the same thing.
clear GLOBAL removes all global variables.
clear FUNCTIONS removes all compiled MATLAB and MEX-functions.
Calling clear FUNCTIONS decreases code performance and is usually unnecessary.

In our previous example, if we would want to clear the variale a, we would use the command

1 >> clear a

If we run the whos command again, we notice that the a is deleted. If we issue the command clear
all, all the variables and deleted and when we run the whos command, we get an empty output since all
the variables have been deleted.

3.2.3 Others
If you hit the up arrow key on the keyboard , and the cursor is in the command window, then you will be
able to see all the list of commands which you have executed. It is like a history of all the commands that
MatLab keeps track of, and it also adds a time-stamp to all those commands

You can use the clc command to clear the screen of the command window.
4. Handling Variables and Creating Scripts

4.1 Understanding Variables


4.1.1 Learning Objectives
Learning the concepts of variables in MATLAB
• How variables are treated as matrices
• Meaning of the size of the variable
• How to define variables in the form of matrices.
• How to deal with variables in the workspace.
In the previous section, we said that a variable contain useful and meaningful data that you would want
to store permanently and may want to use it later for some other purposes or perform more operations on
top of its value.
Lets go back in time and understand the origin of MatLab.
So, what is MatLab and where did MatLab came from?
MatLab stand for Matrix Laboratory. This name has in its way how MatLab handles its variables. By
default, each variable in MatLab is stored inform of a matrix. For example, if we assign 9 to a variable a.
a will be stored as a 1 × 1 matrix. Meaning that a has only one entry.

With that idea in mind, we can go ahead and create variables that have different matrix sizes. Suppose
we want to create a matrix of size greater than one , meaning it will contain more than one item.
We can have multiple rows and columns in a matrix by appending a semicolon as a row delimiter and
by using the square brackets notation . The only catch is that the number of columns must be of the same
22 Chapter 4. Handling Variables and Creating Scripts

size, in the case where you have multiple columns

Our variable a above, is a 3 × 3 matrix. We can verify that by using the whos command and reading its
Size.
When the variable a is created, it is tracked in the workspace. There are a number of statistical
information that can be viewed in the workspace window on the variable, such as, Variance, mean, median,
minimum value, maximum etc

There are also other operations that can be performed on the workspace on the variable. Such as
deleting the variable, duplicating the variable, renaming, etc. Just right click on the variable and select the
operations you wish to perform
4.2 Different Types of Variables 23

We can save also our variables using the .mat extension. This files can be easily loaded in the MatLab
environment and use it.
For example, lets save our variable as matlab file1.mat and clear all the variables in the environ-
ment. Then we load it in the environment. To load it, you can double click it in the current folder window,
and it ill be loaded. Alternatively, you can issue the command

1 >> load('matlab_file1.mat')

We note in the workspace, there contains a variable a which is a 3 × 3 matrix, the one we had created
earlier.

4.2 Different Types of Variables


4.2.1 Learning Objectives
Learning about different types of variables in MATLAB
• Strings
• Numerics
• Logical
In this section, we are going to look at some of the different types of variables that are used in the
MatLab environment. When you create a variable in MatLab, it is allocated its type and its size. This can
be checked using the whos command.

4.2.2 Characters
So far we have been working with a numerical data type. We also have character variables. To create a
character variable, we assing the value in single or double quotes to the variable name.

1 >> name = 'Dr MatLab'

When we run the whos command, we note that its of course a matrix, just as every other variable in
MatLab, and is of class char.
24 Chapter 4. Handling Variables and Creating Scripts

The size is 1 × 9 meaning that it has 9 characters, note white-space(s) is(are) (a) character(s).
We can increase the size of this Matrix in our example above. For example, we would add to the
second row of our matrix the copy of the first row

1 >> name = 'Dr MatLab'


2
3 name =
4
5 'Dr MatLab'
6
7 >> name(2,:) = name(1,:)
8
9 name =
10
11 2x9 char array
12
13 'Dr MatLab'
14 'Dr MatLab'

Note: The matrices have restrictions in that, we can have only rows that have columns of the same size,
for instance, in our example above

1 >> name(3,:) = 'Lets try me'

would cause an error. This is because our matrix is or 9 columns and we’ve provided an entry with 11
columns.

This brings us to the next variable type. If we want to store characters of different sizes, then we would
use the string variables.
4.2 Different Types of Variables 25

4.2.3 String
The string data type is initialized by the reserved1 word string. For example

1 >> greetings = string('Hello, how do you do?')

We note that the variable greetings is of type string by the use of whos command

To store multiple values in the variable, we can use the same idea of square brackets, but specify the
values to be string,

1 >> greetings = [string('Hello, how do you do?') ...


string('How do you do?'); string('Fine') ...
string('Welcome')]

We can access specific value entries of a variable by specifying the row and the column of the value
you wish to get. For example, if we would want to get the value of the first row, the second column .
variablename(rownumber,columnnumber)

1 >> greetings(1,2)
2
3 ans =
4
5 "How do you do?"

1 By reserved, we mean that it cannot be used as a variable name or function name in the matrix programs and scripts since

the MatLab does use it for a specific purpose.


26 Chapter 4. Handling Variables and Creating Scripts

With that idea in mind, we can also change the values of specific entries in a matrix

4.2.4 Logical

This data type can be used to select some data elements from a particular matrix psr store the results of
some Logical decisions and operations you carried out in your programs.
We define a logical variable in this format

1 logi = logical([1 0 1 0; 1 1 0 1])

The logical variable can only have either of two values, that is, 1 or 0. If erroneously define a value greater
than 1, it will be automatically be converted to 1
4.3 Creating Scripts and Understanding Commenting and Semicolon effect 27

4.3 Creating Scripts and Understanding Commenting and Semicolon effect


4.3.1 Learning Objectives
Learning how to create scripts and add useful comments
• Creating scripts from commands history
• Creating scripts as a new file
• Adding comments
• The semicolon effect
So far we have been working on the command window and creating variables. We can however, save
this variables and operations to a file and use them maybe later, or by another program. That is where
scripts comes in. So rather than executing the variables individually in the command line, we can store
this variables and the desired operations in a script.
One way to create a script, is to press the up arrow key and right click to select Create Script

Another window will appear and you can use the window to write your code, and save it, be default in the
current directory, but you can change to the folder of your liking. The extension of the file is .m which is
the MatLab extension for storing scripts
28 Chapter 4. Handling Variables and Creating Scripts

To run the script, you can click the run button on the top bar, or type the script name in the command
window. The code will be executed, and if there are any outputs, they will be printed in the command
window.

We note that our variables are printed in the command window. Suppose we would not want them to
printed, then we would suppress them by appending a semicolon after the statement. We can control the
values to be printed in the command window by the use of a semicolon.
4.3 Creating Scripts and Understanding Commenting and Semicolon effect 29

The statements that has a semicolon at the end, has not been printed in the command window. We will
later look into how to manipulate output and the different ways of formatting the output.

Sometimes, it is needful to add some explanation beside your code, to give some other reader reviewing
your code a brief explanation of what the code is doing. You might also need it and you might want to
know what you thought when making up a certain block of code. This is achieved by what we refer to
as comments. You might have come across comments in other programming languages. MatLab is no
different. It has options to comment out some text or an explanation or an unwanted code.

Comments are the parts of the script which are not executed as part of the program.

To add comments, we need to use a percentage sign % and the text follows will be the comment

1 >> % SOME COMMENTS


30 Chapter 4. Handling Variables and Creating Scripts

The other way to create script is to use the new button in the top bar, click and select New Script, The
other way to create a script is using the shortcut CTRL + N

4.4 Colon and Its Usage


4.4.1 Learning Objectives
Learning how to effectively use the colon
• How to generate numbers with a step size between certain ranges in ascending and descending
order.
4.4 Colon and Its Usage 31

• Data selection with colon.

In this section, we will discuss the uses of : in MatLab. It is very useful especially when you want to
select specific portions of the matrices to perform certain operations on top of that. Understanding of this
concept is very important, for it is a fundamental knowledge for advanced MatLab. Spend adequate time
in this section to make sure you have fully grasped the concept.

The colon is used to generate some numbers. For example, when we specify two positive numbers
before and after the colon, then MatLab is going to generate numbers from the starting number to the last
number (both inclusive), and by default, the increment value is 1

1 >> 1:4
2
3 ans =
4
5 1 2 3 4

Another way to generate numbers with the colon, is by specifying the step size. In other words, the
increment/decrements value. It is specified between the starting number and the ending number also by
use of a colon

1 >> 1:2:8
2
3 ans =
4
5 1 3 5 7
6
7 >> −10:1:−5
8
9 ans =
10
11 −10 −9 −8 −7 −6 −5
12
13 >> 10:−2:5
14
15 ans =
16
17 10 8 6

Lets look at some other functions of the colon. Lets create a matrix of 5 rows and 5 columns randomly
by use of a rand() function. We will dive deeper on rand() functions later. And suppose we want to select
the first three rows, and all the 5 columns.
32 Chapter 4. Handling Variables and Creating Scripts

A hack, if you want to select all columns, or rows, you use just the colon, for example

1 >> mat(:,:)

Will have the same output as just calling the mat variable.
We can perform some other more operations. For example, we could print alternating rows 
mat(1:2:end,:), the end specify the last row. The command will print the first row, skip the second,
print the third, etc to the last row.

We see that, with the help of colon, we can be able to select different subsets or portions of the data, and
Similarly, we can use it to select different columns of the data.
5. Basic Mathematics in MatLab

5.1 Addition, Multiplication, subtraction and powers


5.1.1 Learning Objectives
Learning how to perform basic math in MatLab
• Addition, subtraction, multiplication and power.
In the previous sections, we learnt that every Variable in MatLab is stored as a matrix. Let us define two
matrices and perform some operations on them.
For subtraction, the second matrix will be subtracted from the first one. That is, the corresponding
entries will be subtracted from each other.
34 Chapter 5. Basic Mathematics in MatLab

1 >> mat1 = [1 2 3; 2 3 4]
2
3 mat1 =
4
5 1 2 3
6 2 3 4
7
8 >> mat2 = [3 4 5; 4 5 6]
9
10 mat2 =
11
12 3 4 5
13 4 5 6
14
15 >> mat1 − mat2
16
17 ans =
18
19 −2 −2 −2
20 −2 −2 −2
21
22 >> mat1+mat2
23
24 ans =
25
26 4 6 8
27 6 8 10

We can perform matrix multiplication. However, there is a restriction. As we know for a matrix
multiplication, m × n, the matrices should be m, 2 and 3, n

1 >> one = [1 2; 2 1]
2
3 one =
4
5 1 2
6 2 1
7
8 >> two = [2 2; 3 3]
9
10 two =
11
12 2 2
13 3 3
14
15 >> one*two
16
17 ans =
18
19 8 8
20 7 7

TO get the matrix transpose, we append an apostrophe. See example below

1 >> mat1
2
3 mat1 =
4
5.1 Addition, Multiplication, subtraction and powers 35

5 1 2 3
6 2 3 4
7
8 >> mat1'
9
10 ans =
11
12 1 2
13 2 3
14 3 4

We can decide to have an element by element multiplication operation. And by this, we do not have the
restriction as of the number of rows and columns in the matrices. Rather, we just need the to matrices to
be of the same size. We use the command  mat1 .* mat2

1 >> mat1
2
3 mat1 =
4
5 1 2 3
6 2 3 4
7
8 >> mat2
9
10 mat2 =
11
12 3 4 5
13 4 5 6
14
15 >> mat1 .* mat2
16
17 ans =
18
19 3 8 15
20 8 15 24

Sometime, we might need to raise a number to a certain power. We use the ∧ sign The syntax is as
follows

1 >> num^power

The power can be any number, positive, fraction, negative, etc. Note we can also get powers of matrices,
but it will result to an error if the matrix is not a square matrix.

1 >> a = 10;
2 >> a^2
3
4 ans =
5
6 100
7 >> sq = [1 2; 3 4];
8 >> sq^2
9
10 ans =
11
12 7 10
13 15 22
36 Chapter 5. Basic Mathematics in MatLab

Similarly, we may need to computer power of element by element, we just use the discussed syntax, i.e.,
by use of .∧

1 >> sq .^ 2
2
3 ans =
4 1 4
5 9 16

5.2 Computing GCD, LCM, Permutations and Prime Numbers


5.2.1 Learning Objectives
Learning how to compute with MatLab
• Greatest common divisors
• Least common divisors
• Prime numbers
• Random numbers
• Permutation of numbers
Computing the GCD
GCD - Greatest Common Divisor. MatLab provides a function that calculates the greatest common divisor.
It takes two parameters, and computes the GCD of the two parameters’ values provided. We can also get
the GCD of two matrices
5.2 Computing GCD, LCM, Permutations and Prime Numbers 37

We should note that the input matrices, must be of the same size. The output will also be the same size
as the input matrices. We also note that it is performing GCD element by element of the two matrices.
Another alternative way in which the function GCD may be used is we may pass to it a number and a
matrix containing multiple values.

Computing the LCM


LCM - Least Common Multiple. MatLab also provides a function that calculates the LCM. Similar to
gcd() function, it takes two parameters, and returns the LCM of the two.
38 Chapter 5. Basic Mathematics in MatLab

The is prime function

This function tells us whether or not a certain number is a prime number. It either returns a 0 or a 1.
0 − f alse, 1 − true. The values returned are of type logical.

Similarly, we can check for prime numbers in a matrix,

The Primes function

This function will generate a list of prime numbers. primes(N) is a row vector of the prime numbers
less than or equal to N. A prime number is one that has no factors other than 1 and itself primes(25) will
return prime numbers from 0 upto 25
5.2 Computing GCD, LCM, Permutations and Prime Numbers 39

The prod function


The prod(X) function returns the product of the elements of the vector X. If X is a matrix, the answer is a
row vector with the product over each column

The perms function


This function is going to compute the permutations of the numbers that you pass to it in an array or a matrix.
For example if we have perms([2 3 4]) we are going to have a result of all possible permutations of
this numbers.
Note that if we give the perms function a matrix of more than one rwo, all the values will be treated a
single row matrix and will give you permutation for all the values
40 Chapter 5. Basic Mathematics in MatLab

5.3 Trigonometric Functions

5.3.1 Learning Objectives

Learning trigonometric functions with MatLab


• sin, cos, tan, sec and others in degrees and radians.
• Inverse of sin, cos, sec and others in degrees and radians.
• Degree to radian and radian to degree conversion.

The Sine functions

We use the sin(X) function to get the sine of argument X in radians.


We use the sind(X) function to get the sine of the elements of X , expressed in degrees. For integers n,
sind(n ∗ 180) is exactly zero, whereas sin(n ∗ π) reflects the accuracy of the floating point value of π
5.3 Trigonometric Functions 41

To get the Inverse sine, we use the asin(X) function, which returns the arc-sine of the elements of X.
Complex results are obtained if ABS(x) > 1.0 for some element.

1 >> sin(1)
2 ans =
3 0.8415
4 >> asin(0.841470984)
5 1.0000

If the input is a matrix, then the sin function is going to compute the sine of each element in the matrix.
and the values are going to be radians.

Similar to sin function, we have cos,acos,cosd functions

The Cosine Functions

We use the cosX function to get the cosine of argument (X) in radians. To get the cosine in degrees, we
use the cosd function. Similarly, we get the inverse cosine by acos in radians and acosd in degrees
42 Chapter 5. Basic Mathematics in MatLab

We can also get cosine values for matrix variables


5.3 Trigonometric Functions 43

The Tangent Functions

tan, tand, atan, atand, to compute the tangent of a variable, we use tan to get the result in radians, tand to
get the result in degrees, atan to get the inverse of tan in radians, and atand to get the inverse of tangent
in degrees.

The Secant Functions

sec(X)is the secant of the elements of X.

secd(X) is the secant of the elements of X, expressed in degrees. For odd integers n, secd(n ∗ 90) is
infinite, whereas sec(n ∗ pi/2) is large but finite, reflecting the accuracy of the floating point value for pi.

asecd(X) is the inverse secant, expressed in degrees, of the elements of X.

asec(X) is the inverse secant of the elements of X.


44 Chapter 5. Basic Mathematics in MatLab

The Cosecant Functions

csc(X) is the cosecant of the elements of X.

cscd(X) is the cosecant of the elements of X, expressed in degrees. For integers n, cscd(n ∗ 180) is
infinite, whereas csc(n ∗ pi) is large but finite, reflecting the accuracy of the floating point value for pi.

acscd(X) is the inverse cosecant, expressed in degrees, of the elements of X.

acsc(X) is the inverse cosecant of the elements of X.


5.3 Trigonometric Functions 45

Sometimes we might want to convert our values from radians to degrees or degrees to radians.
To convert radians to degrees we use the rad2deg function.
46 Chapter 5. Basic Mathematics in MatLab

You can always check out the documentation for a detailed list and explanation of more trigonometric
functions, and examples.

5.4 Set Operations

5.4.1 Learning Objectives

Learning Set Operation with MatLab


• Intersection
• Union
• Set difference

Intersection

To get the intersection of two sets, we use the intersect function. It returns the elements that are common
in both inputs.

We can also want to get the indices of the first matrix where the common elements are appearing,
5.4 Set Operations 47

The intersection operation can also be carried out on the individual rows of the matrix. That is, the
intersection is to be performed on rows and not individual elements.
48 Chapter 5. Basic Mathematics in MatLab

We do get the common row in both matrices and we are told in which row number we find that row in the
first matrix.
By default, the intersect function, performs intersections on individual elements.

Union
C = union(A, B) for vectors A and B, returns the combined values of the two vectors with no repetitions.
C will be sorted.
C = union(A, B,′ rows′ ) for matrices A and B with the same number of columns, returns the combined
rows from the two matrices with no repetitions. The rows of the matrix C will be in sorted order.
[C, IA, IB] = union(A, B) also returns index vectors IA and IB such that C is a sorted combination of
the values A(IA) and B(IB). If there are common values in A and B, then the index is returned in IA.
If there are repeated values in A or B, then the index of the first occurrence of each repeated value is
returned.
[C, IA, IB] = union(A, B,′ rows′ ) also returns index vectors IA and IB such that C is the sorted combi-
nation of the rows A(IA, :) and B(IB, :).
[C, IA, IB] = union(A, B,′ stable′ ) for arrays A and B, returns the values of C in the same order that
they appear in A, then B. [C, IA, IB] = union(A, B,′ sorted ′ )returns the values of C in sorted order. If A
and B are row vectors, then C will be a row vector as well, otherwise C will be a column vector. IA and
IB are column vectors. If there are common values in A and B, then the index is returned in IA. If there
are repeated values in A or B, then the index of the first occurrence of each repeated value is returned.
5.4 Set Operations 49

[C, IA, IB] = union(A, B,′ rows′ ,′ stable′ ) returns the rows of C in the same order that they appear in A,
then B. [C, IA, IB] = union(A, B,′ rows′ ,′ sorted ′ ) returns the rows of C in sorted order.
The behavior of union has changed. This includes:
- occurrence of indices in IA and IB switched from last to first
- orientation of vector C
- IA and IB will always be column index vectors
- tighter restrictions on combinations of classes

If this change in behavior has adversely affected your code, you may preserve the previous behavior
with:

1 [C,IA,IB] = union(A,B,'legacy')
2 [C,IA,IB] = union(A,B,'rows','legacy')

Examples:

1 a = [9 9 9 9 9 9 8 8 8 8 7 7 7 6 6 6 5 5 4 2 1]
2 b = [1 1 1 3 3 3 3 3 4 4 4 4 4 10 10 10]
3
4 [c1,ia1,ib1] = union(a,b)
5 % returns
6 c1 = [1 2 3 4 5 6 7 8 9 10]
7 ia1 = [21 20 19 17 14 11 7 1]'
8 ib1 = [4 14]'
9
10 [c2,ia2,ib2] = union(a,b,'stable')
11 % returns
12 c2 = [9 8 7 6 5 4 2 1 3 10]
13 ia2 = [1 7 11 14 17 19 20 21]'
14 ib2 = [4 14]'
15
16 c = union([1 NaN],[NaN 2])
17 % NaNs compare as not equal, so this returns
18 c = [1 2 NaN NaN]

Class support for inputs A and B, where A and B must be of the same class unless stated otherwise:
- logical, char, all numeric classes (may combine with double arrays) - cell arrays of strings (may
combine with char arrays) – ’rows’ option is not supported for cell arrays - objects with methods SORT
(SORTROWS for the ’rows’ option) and NE – including heterogeneous arrays derived from the same root
class

Set Difference
We use the setdiff function to get the set difference of two vectors/matrices
C = setdi f f (A, B)for vectors A and B, returns the values in A that are not in B with no repetitions. C will
be sorted.
C = setdi f f (A, B,′ rows′ ) for matrices A and B with the same number of columns, returns the rows
from A that are not in B. The rows of the matrix C will be in sorted order.
[C, IA] = setdi f f (A, B) also returns an index vector IA such that C = A(IA). If there are repeated
values in A that are not in B, then the index of the first occurrence of each repeated value is returned.
[C, IA] = setdi f f (A, B,′ rows′ ) also returns an index vector IA such that C = A(IA, :).
[C, IA] = setdi f f (A, B,′ stable′ ) for arrays A and B, returns the values of C in the order that they
appear in A. [C, IA] = setdi f f (A, B,′ sorted ′ ) returns the values of C in sorted order. If A is a row vector,
then C will be a row vector as well, otherwise C will be a column vector. IA is a column vector. If there
50 Chapter 5. Basic Mathematics in MatLab

are repeated values in A that are not in B, then the index of the first occurrence of each repeated value is
returned.

1 [C,IA] = setdiff(A,B,'rows','stable') %returns ...


the rows of C in thesame order that they ...
appear in A.
2 [C,IA] = setdiff(A,B,'rows','sorted') %returns ...
the rows of C in sorted order.

The behavior of setdiff has changed. This includes:


- occurrence of indices in IA switched from last to first
- orientation of vector C
- IA will always be a column index vector
- tighter restrictions on combinations of classes
If this change in behavior has adversely affected your code, you may preserve the previous behavior
with:

1 [C,IA] = setdiff(A,B,'legacy')
2 [C,IA] = setdiff(A,B,'rows','legacy')

Examples:

1 a = [9 9 9 9 9 9 8 8 8 8 7 7 7 6 6 6 5 5 4 2 1]
2 b = [1 1 1 3 3 3 3 3 4 4 4 4 4 10 10 10]
3
4 [c1,ia1] = setdiff(a,b)
5 % returns
6 c1 = [2 5 6 7 8 9]
7 ia1 = [20 17 14 11 7 1]'
8
9 [c2,ia2] = setdiff(a,b,'stable')
10 % returns
11 c2 = [9 8 7 6 5 2]
12 ia2 = [1 7 11 14 17 20]'
13
14 c = setdiff([1 NaN 2 3],[3 4 NaN 1])
15 % NaNs compare as not equal, so this returns
16 c = [2 NaN]

5.5 Computing Statistics of the Matrices


5.5.1 Statistical Functions
Learning Objectives
Learning to compute statistical operations
• Minimum, Maximum, Mean, Mode, standard deviation, Variance and Percentile.
In this section, we will be looking at different statistical information that can be performed on matrices.
In particular, we will be learning some of the statistical funcitons that you can apply with the MatLab
Let us define a matrix

1 >> a = [5 8 9; 8 7 9; 1 9 3];

min(a) will return the minimum of each column,


5.5 Computing Statistics of the Matrices 51

1 >> min(a)
2 ans =
3 1 7 3

If we want to compute the minimum across the rows, we would use the transpose of our matrix

1 >> min(a')
2 ans =
3 5 7 1

The min function has a number of options. We may be interested to get the index positions of the minimum
values of our matrix.

Another way to get the minimum values across the rows is by adding the square brackets parameter and 2
for rows, 1 for columns
52 Chapter 5. Basic Mathematics in MatLab

Similar to min function is the max function. It has pretty the same options as the min functions, save
that it returns maximum values
5.5 Computing Statistics of the Matrices 53

The mean functions returns the mean. When we pass to it a matrix, it returns the mean across the columns.
But we can specify whether we want the mean of the columns or the rows by adding another argument, 1
for columns , 2 for rows.

1 >> a
2
3 a =
4
5 5 8 9
6 8 7 9
7 1 9 3
8
9 >> mean(a)
10
11 ans =
12
13 4.6667 8.0000 7.0000
14
15 >> mean(a,1)
16
17 ans =
18
54 Chapter 5. Basic Mathematics in MatLab

19 4.6667 8.0000 7.0000


20
21 >> mean(a,2)
22
23 ans =
24
25 7.3333
26 8.0000
27 4.3333
28
29 >>

The var function is used to get the variance.


The std function is used to get the standard deviation.
The sum function is used to get the sum of the elements
The median function is used to get the median value(s).
The prctile function is used to get the Percentile. Note we need to specify what Percentile we are
interested in. For example, if we wanted to get the 25 f h percentile of Matrix a, then prctile(a, 25). If
you are interested in multiple percentiles, then you would specify the percentiles in a square brackets
prctile(a, [2550]). In addition, you can specify whether you are interested in rows’ percentiles or columns.
prctile(a, [2550], 1) 1 for columns, 2 for rows.
The mode function is used to get the value which is most frequent in a matrix.
Note: To get the minimum value in a square matrix, we can use the min function twice. min(min(a)).
that goes for maximum as well.

1 >> a
2 a =
3 5 8 9
4 8 7 9
5 1 9 3
6 >> var(a)
7 ans =
8 12.3333 1.0000 12.0000
9 >> std(a)
10 ans =
11 3.5119 1.0000 3.4641
12 >> sum(a)
13 ans =
14 14 24 21
15 >> sum(a,2)
16 ans =
17 22
18 24
19 13
20 >> median(a)
21 ans =
22 5 8 9
23 >> median(a,1)
24 ans =
25 5 8 9
26 >> median(a,2)
27 ans =
28 8
29 8
30 3
31 >> prctile(a,25)
32 ans =
5.6 Random Numbers 55

33 2.0000 7.2500 4.5000


34 >> prctile(a,[25 50 75])
35 ans =
36 2.0000 7.2500 4.5000
37 5.0000 8.0000 9.0000
38 7.2500 8.7500 9.0000
39 >> mode(a)
40 ans =
41 1 7 9
42 >> mode(a,1)
43 ans =
44 1 7 9
45 >> mode(a,2)
46 ans =
47 5
48 7
49 1
50 >> min(min(a))
51 ans =
52 1
53 >> max(max(a))
54 ans =
55 9

5.6 Random Numbers

5.6.1 Learning Objectives

Learning different ways of generating random numbers

• Random numbers generation.


• Random numbers generation in a range.
• Random numbers generation based on normal distribution.
• Random permutations.

The rand function generates random numbers. If we specify not the rows, or columns, but one value,
the rand create a square matrix of size that value of random numbers. This function considers a uniform
distribution
56 Chapter 5. Basic Mathematics in MatLab

The randn function generates random numbers with a normal distribution. This function considers a
normal distribution for generating random values.

The randperm function. p = randperm(n) returns a row vector containing a random permutation of the
integers from 1 to n without repeating elements.
5.6 Random Numbers 57

p = rand perm(n, k) returns a row vector containing k unique integers selected randomly from 1 to n.

Sometimes, we may want to change the range of values for which you are interested in computing
thier corresponding permutations. For instance, we may want to get random permutations between 2 and
7,
58 Chapter 5. Basic Mathematics in MatLab

The randi function generate pseudorandom integers from a uniform discrete distribution
5.7 Cross and Dot Product 59

5.7 Cross and Dot Product

5.7.1 Learning Objectives

Learning how to perform cross and dot products


• Different ways in which the two products can be implemented.

5.7.2 The Dot Product

MatLab provides a function,dot, that computes the dot product of two vectors. Let us first understand the
dot product .
In mathematics, the dot product or scalar product is an algebraic operation that takes two equal-length
sequences of numbers (usually coordinate vectors), and returns a single number. Refer to Wikipedia Dot
Product for more understanding.
60 Chapter 5. Basic Mathematics in MatLab

If the input are matrices, the dot product will be evaluated based on columns. To get the dot product
of rows, you can use matrices transpose, or add 2,
5.7 Cross and Dot Product 61

1 >> dot(mat1,mat2,2)
2 ans =
3 26
4 47

5.7.3 The Cross Product

The cross function calculates the cross product of two matrices. The matrices here must be of 3 dimension.
62 Chapter 5. Basic Mathematics in MatLab

5.8 Logic Operations


Learning Objectives

Learning Logic Operations


• Logical AND operation
• Logical OR operation
• Logical NOT operation
Suppose we have two vectors A, and B

1 >> A
2 A =
3 1 5 8 7 0
4 >> B
5 B =
6 1 1 0 2 3

5.8.1 The and operator


Calling the and(A,B) function with the two vectors as argument parameters , it will compute the logical
operation between the elements of A and B on element by element basis. In that case, when the both
matrices have a non-zero value, it will return a value of 1 and if any one of them is containing a value of 0
then it will return a value of zero.
5.8 Logic Operations 63

Similarly in order to perform the same operation, we can use A & B syntax

1 >> A & B
2 ans =
3 1x5 logical array
4 1 1 0 1 0
5 >>

Alternatively, if you pass to this function a vector and some constant value that is either 1 or 0, then its
going to perform the logical and operation between the constant value and the values of the matrix.

1 >> A
2 A =
3 1 5 8 7 0
4 >> A & 0
5 ans =
6 1x5 logical array
7 0 0 0 0 0
8 >> A & 1
9 ans =
10 1x5 logical array
11 1 1 1 1 0

5.8.2 The or operator


To perform a logical addition between two vectors, we use the or function. or(A,B) is going to compute
the logical addition between the respective elements of the two vectors, A and B. If any one of the values
which is taking part in the or operation is a non-zero value then the result is going to be a logical one. If
both values that are taking part in the or operation are 0, then the result is going to be a logical 0.
64 Chapter 5. Basic Mathematics in MatLab

1 >> or(A,B)
2 ans =
3 1x5 logical array
4 1 1 1 1 1
5 >> A(3) = 0 % Changing the third value in A ...
to 0
6 A =
7 1 5 0 7 0
8 >> or(A,B)
9 ans =
10 1x5 logical array
11 1 1 0 1 1

Another way of achieving the same, is by use of the pipe symbol |,

1 >> A | B
2 ans =
3 1x5 logical array
4 1 1 0 1 1

5.8.3 The not operator


To perform a logical not operation, we use the function not and pass to it a certain variable or a matrix.
Basically, the not function, will perform the negation of a variable passed.

1 >> not(A)
2 ans =
3 1x5 logical array
4 0 0 1 0 1
5 >> A|B
6 ans =
7 1x5 logical array
8 1 1 0 1 1
9 >> not(A|B)
10 ans =
11 1x5 logical array
12 0 0 1 0 0

The other way to perform the same operation, is by use of the ∼ sign.

1 >> ¬A
2 ans =
3 1x5 logical array
4 0 0 1 0 1
5 >> ¬(A|B)
6 ans =
7 1x5 logical array
8 0 0 1 0 0
9 >>

5.9 Sign and Absolute Functions


Learning Objectives
Learning sign and absolute functions
5.9 Sign and Absolute Functions 65

• SIgn function on real and imaginary numbers.


• Absolute function on real and imaginary number

5.9.1 The sign functions


This function can take four different kinds of inputs. If we pass a value greater than zero, it is going to
return 1. If we pass to it a value that is equal to zero, then it will return a value of zero. If we pass a value
that is less than zero, then it is going to return a value of minus one. If we pass to it a complex number,
then it is going to return a different output. A real part and an imaginary part. We will explain this result
later

1 >> sign(+10)
2 ans =
3 1
4 >> sign(−10)
5 ans =
6 −1
7 >> sign(0)
8 ans =
9 0
10 >> d = 3+6i
11 d =
12 3.0000 + 6.0000i
13 >> sign(d)
14 ans =
15 0.4472 + 0.8944i
16 >>

5.9.2 The abs function


This function is going to return the absolute value for any number that we pass to it as an argument.

1 >> abs(+10)
2 ans =
3 10
4 >> abs(−10)
5 ans =
6 10
7 >> abs(0)
8 ans =
9 0
10 >> abs(d)
11 ans =
12 6.7082
13 >> d
14 d =
15 3.0000 + 6.0000i
16 >> % D IS THE SQUARE ROOT OF (−45): (3^2 + 6^2) x −1
17 >> % SO GETTING THE ABS OF d, IS LIKE
18 %COMPUTING THE SQUARE ROOT OF 45
19 >> abs(d)
20 ans =
21 6.7082
22 >> sqrt(45)
23 ans =
24 6.7082
25 >> sqrt(−45)
66 Chapter 5. Basic Mathematics in MatLab

26 ans =
27 0.0000 + 6.7082i
28 >> abs(sqrt(−45))
29 ans =
30 6.7082
31 >>

Let us go back now and explain the sign() results of a complex number. Basically, it is going to divide
the value in the real part and the value in the imaginary part by the absolute value of that number.

1 >> d
2 d =
3 3.0000 + 6.0000i
4 >> abs(d)
5 ans =
6 6.7082
7 >> 3/(abs(d))
8 ans =
9 0.4472
10 >> 6/(abs(d))
11 ans =
12 0.8944
13 >> sign(d)
14 ans =
15 0.4472 + 0.8944i
16 >>

Finally, if you pass vector in the sign function, it is going to compute the sign, element by element. The
same goes for matrices variables. And also the same applies to abs function.

1 >> vec1 = [1,2,3,4]


2 vec1 =
3 1 2 3 4
4 >> vec1(5) = −4
5 vec1 =
6 1 2 3 4 −4
7 >>
8 vec1(6) = 0
9 vec1 =
10 1 2 3 4 −4 0
11 >> sign(vec1)
12 ans =
13 1 1 1 1 −1 0
14 >> mat1 = [1 2 3; 4 5 6; 7 8 9]
15 mat1 =
16 1 2 3
17 4 5 6
18 7 8 9
19 >> sign(mat1)
20 ans =
21 1 1 1
22 1 1 1
23 1 1 1
24 >> abs(mat1)
25 ans =
26 1 2 3
27 4 5 6
28 7 8 9
29 >>
5.10 Number Conversions 67

5.10 Number Conversions


Learning Objectives
Learning to convert numbers between different bases
• Base 10 to any other base conversion.
• From any other base to base 10 conversion
• From any base to any other base conversion

5.10.1 The dec2base Function


This function requires two arguments. The first argument is the number that we want to convert from
decimal to any other base. For instance, we want to convert 100, which is in base 10 , to base 2

1 >> dec2base(100,2)
2 ans =
3 '1100100'

If the input is a matrix, the elements in the matrix are going to be converted to the said base.

1 >> mat1
2 mat1 =
3 1 2 3
4 4 5 6
5 7 8 9
6 >> dec2base(mat1,2)
7 ans =
8 9x4 char array
9 '0001'
10 '0100'
11 '0111'
12 '0010'
13 '0101'
14 '1000'
15 '0011'
16 '0110'
17 '1001'
18 >>

5.10.2 The base2dec function


This function requires two parameters, the first being the number format in another base that we are
interested to convert to decimal. This argument must be in character format, meaning that it must be
enclosed in single quotes. The second argument is the base of the first argument.

1 >> dec2base(8,2)
2 ans =
3 '1000'
4 >> base2dec('1000',2)
5 ans =
6 8
7 >> dec2base(100,16)
8 ans =
68 Chapter 5. Basic Mathematics in MatLab

9 '64'
10 >> base2dec('64',16)
11 ans =
12 100
13 >>

Note: If you pass the incorrect number format base in the second argument, it is going to return an error.

There are also other functions bin2dec,dec2bin that converts binary number to decimal and decimal to
binary respectively. But the dec2base,base2dec are more general.

1 >> x = base2dec('1111',2)
2 x =
3 15
4 >> dec2base(x,16)
5 ans =
6 'F'
7 >> dec2base(x,17)
8 ans =
9 'F'
10 >> dec2base(x,10)
11 ans =
12 '15'
13 >> dec2base(x,4)
14 ans =
15 '33'
16 >> dec2base(x,5)
17 ans =
18 '30'
19 >> dec2base(x,6)
20 ans =
21 '23'
22 >>

5.11 Discretizing your Data


Learning Objectives
Learning different ways of discretization of data
• Discretization using fixed predefined bin
• Discretization using equal sized bins
• Discretization using the left edge of intervals
• Discretization using the right edge of intervals
In this section, we are going to learn how to discretize your data using MatLab. The function we are
going to use to achieve this is the discretize function. As an input, this function requires a number of
levels which you want to discretize your data into. This levels are sometimes known as bins. The first step
is to identify the bins or levels.
Suppose we have this data

1 >> data = [1 1 2 3 6 5 8 10 4 4];


5.11 Discretizing your Data 69

We define the bins

1 >> edges = 2:2:10;

We discretize our data

1 >> Y1 = discretize(data,edges)
2 Y1 =
3 NaN NaN 1 1 3 2 4 4 2 2

This edges = 2:2:10 means that

1 >> % bin 1 : 2 − 3.9999. Note that 4 is note included


2 >> % bin 2 : 4 − 5.9999
3 >> % bin 3 : 6 − 7.9999
4 >> % bin 4 : 8 −10. Note 10 is included in the last bin

The result we get, tells us that 1 does not fall in any bin, 2 falls in the first bin, 3 falls in the first bin and so
on.
Suppose we want to include the right edges, that is include 4 in our example above in bin 1, then

1 >> Y2 = discretize(data, edges, 'IncludeEdge', 'right')


2 Y2 =
3 NaN NaN 1 1 2 2 3 4 1 1

The bins now will be

1 >> % bin 1 : 2 − 4
2 >> % bin 2 : 4.01 − 6
3 >> % bin 3 : 6.01 − 8
4 >> % bin 4 : 8.01 − 10

We can define our edges in a matrix format

1 >> edges = [1 3 4 7 10 11];

The bins now will be, based on the default option of the edges being set on the left

1 >> % bin 1 : 1 − 2.99


2 >> % bin 2 : 3 − 3.99
3 >> % bin 3 : 4 − 6.99
4 >> % bin 4 : 7 − 9.99
5 >> % bin 5 : 10 − 11
6 >> Y1 = discretize(data, edges)
7 Y1 =
8 1 1 1 2 3 3 4 5 3 3

We might want not to specify the edges but rather specify the number of bins in which we want to
discritize our data into.

1 >> [Y, E] = discretize(data,3)


2 Y =
70 Chapter 5. Basic Mathematics in MatLab

3 1 1 1 1 2 2 3 3 2 2
4 E =
5 0 4 8 12

MatLab computes the minimum and the maximum values in our data, and then divides the bins into the
number provided as the second argument in the discretize function. Note that by default, it is going to set
the edges on the left. You can change that by adding some more parameters like we did before. That is

1 [Y, E] = discretize(data, 4, 'IncludeEdge', 'right');


5.12 Practice Exercise Questions 71

5.12 Practice Exercise Questions


1 You have a matrix for which each row is a person and the columns represent the number of quarters,
nickels, dimes, and pennies that person has (in that order). A value of one in the matrix means that
the respective person has a certain coin with him. You are required to determine the row index of
the person with the most money? For instance, if we have the input matrix A = [1 0 0 0; 0 1 0 0; 1
1 1 0] than the output should be 3. Since the total amount with person 3 is $0.40. Note for those
unfamiliar with American coins: quarter = $0.25, dime = $0.10, nickel = $0.05, penny = $0.01.
2 The following two equations are used to change the temperature between Fahrenheit and centigrade.
From centigrade to Fahrenheit F = (9/5 *C) +32
From Fahrenheit t to centigrade C = (F - 32) * 5/9.
Write MATLAB expression for converting a temperate from Fahrenheit to centigrade and from
centigrade to Fahrenheit. Make sure you use the brackets correctly.
3 Given two list of numbers (1D matrices), determine the weighted average. For instance, if we have
A =[1 2 3] and B = [10 15 20] than the result should compute (1*10 + 2*15 + 3*20)/3 which is
33.3333
4 Given two lists of numbers or sets A and B, check to see if their intersection is empty or not. If it is
empty than the statement should return a logical 0, otherwise it should return a logical 1.
Hint: isempty() function tells you if a matrix is empty of not
5 There are two lists or 1D matrices namely A and B. The first list i.e., A is showing the prices of the
items and the second one, i.e., B is showing how much quantity of each item was being bought by a
customer. Write a MATLAB statement that will show the total final bill of a customer.
6. Operations on Matrices

6.1 Computing Unique Elements


Learning Objectives
Learning how to compute unique elements of matrices
• Column wise unique elements
• Row wise unique elements
• Matrix wise unique elements
• Location of unique elements
In this section, we will be looking at how to effectively manipulate the matrices and perform different
operations on the matrices. This is where the power of MatLab comes into play.
We will begin by performing a unique operation, that will return the elements that are unique in the
matrix.
The unique built-in MatLab function is going to perform this operation.

1 >> mat1
2 mat1 =
3 1 2 3
4 4 5 6
5 7 8 9
6 >> unique(mat1)
7 ans =
8 1
9 2
10 3
11 4
12 5
13 6
14 7
15 8
16 9
17 >> mat1(4,:) = [1 5 9]
18 mat1 =
19 1 2 3
20 4 5 6
21 7 8 9
22 1 5 9
74 Chapter 6. Operations on Matrices

23 >> unique(mat1)
24 ans =
25 1
26 2
27 3
28 4
29 5
30 6
31 7
32 8
33 9
34 >>

We note that 1, 5, 9 are repeated twice. By default, the result contain the unique values in sorted order,
(ascending). Also note that the result is a vector. By default it computes the unique elements both in the
rows and the columns. To specify whether you are interested in the rows or columns, you might need to
specify in the unique function. For example, if we want to check the unique elements in the first column,
then we would use  unique(mat1(:,1)), which means that all rows, but only the value in the first
column.

1 >> unique(mat1(:,1))
2 ans =
3 1
4 4
5 7
6 >>

We might be interested to get the indices of the unique elements in the matrix. We achieve this by
calling our unique function with two outputs, the unique element, and the position it is found.

1 >> [C, ia] = unique(mat1)


2 C =
3 1
4 2
5 3
6 4
7 5
8 6
9 7
10 8
11 9
12
13 ia =
14 1
15 5
16 9
17 2
18 6
19 10
20 3
21 7
22 11
23 >>

To interprate the indices output, the MatLab counts the elements of the matrix in a column-wise fashion,
thus, in our matrix example above, the first element in the second column, will be the forth position.
If you are interested in locating the individual elements in the matrix in the unique element in C. We
6.1 Computing Unique Elements 75

specify three outputs in our unique function.

1 >> [C ia ib] = unique(mat1)


2 C =
3 1
4 2
5 3
6 4
7 5
8 6
9 7
10 8
11 9
12
13 ia =
14 1
15 5
16 9
17 2
18 6
19 10
20 3
21 7
22 11
23
24 ib =
25 1
26 4
27 7
28 1
29 2
30 5
31 8
32 5
33 3
34 6
35 9
36 9

Lets get the transpose of ia, ib and C

1 >> ia'
2 ans =
3 1 5 9 2 6 10 3 7 11
4 >> ib'
5 ans =
6 1 4 7 1 2 5 8 5 3 6 ...
9 9
7 >> C'
8 ans =
9 1 2 3 4 5 6 7 8 9
10 >> mat1
11 mat1 =
12 1 2 3
13 4 5 6
14 7 8 9
15 1 5 9
16 >>
76 Chapter 6. Operations on Matrices

Lets consider element 1 in our matrix, It is located in the first position, so in our ia it is 1, now ib will tell
us in what position do we find 1 of the matrix C in the ia, which is in this case 1.

6.2 Membership and Equality

Learning Objectives

Learning the membership and equality functions

• How to check the membership of an element wit a matrix in row wise and column wise fashion.
• How to check for equality of rows, columns and individual elements of a matrix.

6.2.1 The ismember function

Suppose we have

We are interested in finding whether or not a certain element belongs to this matrix. The ismember
function is used to achieve this.

In this case, we call the ismember function with two arguments. The first parameter is the element to
look for and the second parameter is the matrix to look into. This function returns a logical value. 1 if the
value is found in the matrix, and 0 if the value is not found.
6.2 Membership and Equality 77

If we pass to this function two matrices, where one of the matrices is a vector, and the other parameter
a matrix, the ismember function will check whether the vector elements are found in the matrix or not.
78 Chapter 6. Operations on Matrices

If we want to locate the indexes of the values as well, then we need to specify additional output of the
ismember function.

We can also check if a particular row is contained in a matrix is not.

6.2.2 The isequal function


We can check if two elements are equal or not. Or even matrices. The function returns to true if the two
elements are equal. False 0,otherwise.

1 >> isequal(x,y)
2 ans =
3 logical
4 0
5 >> x
6 x =
7 5 9 8
8 4 5 6
9 8 7 9
10 1 2 3
11 >> y
12 y =
13 3 2 1
6.3 Shifting Matrix Elements 79

14 2 1 3
15 >> isequal(x,y)
16 ans =
17 logical
18 0
19 >>

We can also check if the matrices are equal in size and also in their contents by changing the input
slightly

6.3 Shifting Matrix Elements


Learning Objectives
Learning how to shift the elements of a Matrix
• Shifting elements of the matrix row wise up and down.
• Shifting elements of the matrix column wise to the left and to the right.

6.3.1 Shifting Matrix Elements


We will be looking at how to shift elements of the matrix both row wise and column wise.
Lets have a matrix
80 Chapter 6. Operations on Matrices

The function we need to perform the row/column shift operation is known as the circshift function.
The first argument is the matrix that you want to perform the shift operation which in our example is
matrix A. The second argument specifies the amount of shift we want to apply on the row and columns, it
will contain two values in a square brackets. The first one indicating the amount of shift we want to apply
on the rows, and the second one indicating the amount of shift we want to apply in the columns.
In this case, 0 means we do not want to shift the rows , however the 2 in the second place means that
we want to shift the columns 2 places. If there is a positive value, which in this case is, then it means a
shift to the right. If negative, means a shift to the left.
6.4 Matrix Operations 81

6.4 Matrix Operations


Learning Objectives
Learning commonly used matrix operations
• Determinant
• Inverse
• Diagonal of a matrix.

6.4.1 Inverse of a matrix


To compute the inverse of a matrix in MatLab, we use the inv function and pass the matrix as the argument.

The other way is raising the matrix to the power of −1.


82 Chapter 6. Operations on Matrices

6.4.2 Determinant of a matrix

To compute the determinant of a matrix in MatLab, we use the det function and pass the matrix as the
argument.

6.4.3 Diagonal Elements of a Matrix

To compute the diagonal elements of a matrix in MatLab, we use the diag function and pass the matrix as
the argument.

If we pass a vector to the diag function, all the elements in the vector are placed diagonally in the result,
and all other entries are filled with zeros.

If we pass another argument in the diag function, a number, if the number is positive, we get the elements
of the diagonal nth diagonal from the main diagonal moving towards right hand side. If the number is
negative, then nth diagonal from the main diagonal moving towards the left hand side. If the number is
zero, of course, remains to be the main diagonal.
6.4 Matrix Operations 83
84 Chapter 6. Operations on Matrices

6.5 Relational Operations


Learning Objectives
Learning mathematical relational operations and how to store them in logical variables
• How to compute greater, greater than,lee, less than, equal to and not equal To

6.5.1 Greater than or equal to


If we have a Matrix and want to compute if the elements of the matrix are greater than or equal to a certain
value, we use the ge function that takes two arguments. The first one is the matrix, and the second one is
the number. The result is a logical array, that shows 0 when false and 1 when true.

Another way to achieve that is by use of ≥


6.5 Relational Operations 85

If we pass two matrices in our function, the function will compute element by element comparison.

6.5.2 Greater than


The function we use here is gt. It strictly for greater than.
86 Chapter 6. Operations on Matrices

6.5.3 The Less Than

We use the lt. It strictly checks for less than and no equality
6.5 Relational Operations 87

We can also use the < operator.

6.5.4 The Less Than or equal to

The function we use here is le.


88 Chapter 6. Operations on Matrices

We can also use the ≤ operator

6.5.5 The Not Equals To operation

It is specified by ne function and returns a logical array.


It is the opposite of the is equal to function
6.5 Relational Operations 89

We can also compare strings and check for their equality the very same way we check for the numerical
values.
90 Chapter 6. Operations on Matrices

6.6 Common Matrices


Learning Objectives
Learning commonly used matrices in MatLab
• The matrix containing all ones.
• The matrix containing all zeros.
• The magic matrix.

6.6.1 The Matrix of Ones


The function ones is used to generate square matrix of the size you passed and all entries are 1s . If you
specify the second argument, then the matrix created will have the number of columns specified in the
second argument.

6.6.2 The Matrix of zeros


The function zeros is used to generate square matrix of the size you passed and all entries are 0s . If you
specify the second argument, then the matrix created will have the number of columns specified in the
second argument.
6.7 Sorting Matrix Values 91

The Magic Square Matrix

The function magic is used to create square matrix, which are magic squares. It only works with square
matrices. A magic square matrix, is one in which the sum or rows, the columns, diagonals is the same.

6.7 Sorting Matrix Values

Learning Objectives

Learning how to sort matrix values


• Sorting values in ascending and descending order.
• Indexes of values after being sorted.
• Sorting row wise and column wise.
• Sorting non-numeric values.

6.7.1 Sorting Values

The function sort is used to sort the values in a matrix. By default, it is going to sort in an ascending order.
92 Chapter 6. Operations on Matrices

If we need the result in descending order, we need to specify another argument

We might want to know the indeces of the sorted values, at what position do they appear in the original
matrix.

If our input matrix is a multi dimensional matrix, the columns are going to be sorted individually.
By default in ascending order. but we can specify whether we are interested in sorting the rows or the
columns and whether its descending or ascending.
6.7 Sorting Matrix Values 93

The sorting function also applies to string values. And calling the sort function with string values as
parameters, it will sort he strings with respect to the first character in ascending order by default.

If there exist more than one string with the same character, then the sort function picks this strings
and compares their next characters, all the way, until it get the ’greater’ one. It also first checks for the
capitalized letters first, then it proceed to the lowercase letters.
94 Chapter 6. Operations on Matrices

This function can also be applied to sort character arrays.

6.8 Size and Length Functions


Learning Objectives
Learning how to obtain size related information of a matrix.
• Rows and column information of a matrix
• size of matrix with non-numeric data.
• Length of a string.
In this section, we will learn how to compute the size and length of matrices. That is, how to get the
information regarding the number of elements contained within our matrices.
6.9 The size function 95

6.9 The size function

This function returns the number of rows of a matrix and the number of columns of the same matrix as
well.

6.10 The length function

The difference between the length function and the size function, is that the length function is going to
return a dimension for a matrix that has the highest value. Meaning, if the number of rows are more than
the number of columns, then it will return the number of rows, and the converse applies.
96 Chapter 6. Operations on Matrices

We can also check the length of string arrays, but to get the number of characters in a string, we use
the strlength function.
6.11 Matrix Concatenation 97

6.11 Matrix Concatenation


Learning Objectives

Learning how to concatenate matrices.


• Rows wise concatenation of matrices.
• Columns wise concatenation of matrices.
We can concatenate matrices by either rows or columns.

6.11.1 Matrices Row Concatenation

Suppose we have two matrices

1 >> M1
2 M1 =
3 0.8147 0.9134 0.2785
4 0.9058 0.6324 0.5469
5 0.1270 0.0975 0.9575
6 >> M2
7 M2 =
8 0.9649 0.1576 0.9706

If we want to concatenate the two matrices and store them in another matrix variable, then , we use the
square brackets, and the matrices separated by a semicolon. Note that the order is very important. Also
the number of rows of columns of the two matrices we want to concatenate should be the same.

6.11.2 Matrices Columns Concatenation

For this case, the two matrices need to have the same number of rows. We use a space delimiter and not a
semicolon
98 Chapter 6. Operations on Matrices

Lets note also that the order is very important.

6.12 Finding Non-Zero Elements


Learning Objectives
Learning how to find non-zero elements
• Finding non-zero elements at the beginning and at the ending of a matrix.
• Computing the indexes of the non-zero elements.
6.12 Finding Non-Zero Elements 99

We will be using the find function that extract the non-zero elements from a matrix or a vector.
Suppose we have a matrix that has both zeros and no zeros. Calling the find function, it will return, in
a column wise fashion, the indexes of the non-zero elements in the matrix.

We can mention a second argument in the find function. In that case, if the second argument is number N,
then the result will be indexes of the first N non-zero elements.

If we want to get the last n elements, then we will specify an additional argument
100 Chapter 6. Operations on Matrices

Another useful variant of this function, is hat if you want to have the row and column information
corresponding to non-zero elements, this means now that we do not want the linear indexes, but rather the
specific row and specific column in the Matrix which contains the non-zero elements. To achieve that, we
mention two outputs with the function is square brackets and cal the same function.

Now we can see in what row and what column the first non-zero element appear in the Matrix.

6.13 Frequency of Values within a Vector


Learning Objectives
Learning how to determine frequencies of values
6.13 Frequency of Values within a Vector 101

• Frequencies of values in a vector.


• Frequencies of values in a matrix.
• Frequencies of values in a sub-matrix.

The function tabulate returns some statistical information of a vector

TABLE = tabulate(X) takes a numeric vector X and returns a numeric matrix, TABLE. The first
column of TABLE contains the unique values of X. The second is the number of instances of each value.
The last column contains the percentage of each value. If the elements of X are positive integers, then the
output includes 0 counts for any integers that are between 1 and max(X) but do not appear in X.

TABLE = tabulate(X), where X is a logical vector, categorical variable, character array, string array,
or a cell array of strings, returns TABLE as a cell array. The first column contains the unique string values
in X, and the other two columns are as above.

tabulate with no output arguments returns a formatted table in the command window.

We can specify specific rows or columns in the tabulate function.


102 Chapter 6. Operations on Matrices
6.14 Practice Exercise 103

6.14 Practice Exercise


1 Write a single statement for finding the indexes of positive values using the f ind() function. For
instance, if Suppose Q = [4 5 6 0 0 1 2 3 -1 -2] then the statement should return 1 2 3 6
7 8
2 Write a statement that will reverse the order of the values in a vector. For instance, if X =
[456123]then the statement should display 3 2 1 6 5 4
3 Write a statement that displays the values at the odd indexes of an array (consider array to be a
matrix with one dimension).
4 Consider a 10 × 10 matrix A = rand(10). Extract the lower right 5 × 5 matrix using a single matrix
command. Please note that the resultant matrix should have a size of 5 × 5.
5 Consider a one dimensional matrix A = [8 9 7 4 5 2 6 5 4 1 3 9 8 7 5 2 3]. Write a
single statement which will return all unique elements from the matrix A which are greater than or
equal to 2 and less than or equal to 5.
6 Consider a one dimensional matrix A such as A = [5 8 8 8 9 9 6 6 5 5 4 1 2 3 5 3 3 ].
Show the percentage frequencies of unique elements in the matrix A in descending order.
Hint: use the functions tabulate and sort
7 Write a statement that will delete the elements with value of 0 from a single dimensional matrix A.
8 Generate an array of 10 random numbers between 1 and 100. Then find out how many of the
elements are between 1 and 25, how many between 25 and 75 and how many between 75 and 100.
9 Consider a variable X that contains some string. We want to display the contents of the string in
alphabetical order (i.e., hello becomes ehllo). Assume numbers and punctuation symbols will not
be included in the string. Write a MALTAB statement that will do this job for us.
10 Write a MATLAB statement that will compute index of the row with the most nonzero elements in
a 2D matrix. Assume there will always be exactly one row that matches this criterion.
Check out for solutions: 13.2

6.15 Practice Exercise Advanced


1. Consider an n × n matrix A = rand(n) where n is any positive number greater than 2. Write a
statement which will return the four corner elements of the matrix A in a 2 × 2 matrix R such that
R(1,1) is the upper right corner element,
R(1,2) is the upper left corner element,
R(1,3) is the lower right corner element, and
R(1,4) is the lower left corner element.
2. A word is said to palindrome if it reads the same backwards as forwards. Let X be a string containing
some word, use MATLAB statements to check whether the word contained in X is a palindrome or
not? The statement should return a logical 1 if it is a palindrome and 0 otherwise. Assume that the
word should only contain letters from a - z or A - Z
3. Consider an M*N matrix A. Write a command for deleting one entire row or column. For instance,
A = rand(5). Now I want to delete the third row.
4. Let us suppose we define the following five matrices.

a = [1; 2; 3]; b = [4; 5; 6]; c = [7; 8; 9]; A = [a, b, c]; B = [a, b];

Which of the following are not correct statements (will give out an error message)?
10.1. a+b
10.2. a*b
10.3. a.*b
10.4. A*b
10.5. A.*b
104 Chapter 6. Operations on Matrices

10.6. a’*b
10.7. a*b’
10.8. A*A
10.9. A.*A
10.10. A*B
10.11. A.*B
10.12. B*A
10.13. B*B
5. Consider the following three row vectors or one dimensional arrays.

A = [8 9 10 11].

B = [5]
C = [9 8 5]
We want to collect all these vectors in one single matrix such that the all the entries are aligned
from the right and if an entry is missing we will add a leading zero in the matrix from the left. The
results matrix should look something like this.

1 X = [8 9 10 11
2 0 0 0 5
3 0 9 8 5].

Write MATLAB statements that will do this operation.


6. Find a short MATLAB command that will build the following matrix

1 A = [ 1 2 3 4 5 6 7
2 9 7 5 3 2 −1 −3
3 4 8 16 32 64 128 256]

Note: try to detect the sequence in each row and then use the : operator.
7. What will be the result of applying the command [0 0 1 ]*A to the following matrix.

1 A = [ 4 5 6 9
2 7 8 9 9
3 8 7 4 5]

8. What will be the result of applying the command [1 0 0; 0 0 1; 0 1 0] * A to the following


matrix

1 A = [ 4 5 6 9
2 7 8 9 9
3 8 7 4 5]

Check out for solutions: 13.3


7. Math Functions with Symbolic Data Types

7.1 Symbolic Variables

Learning Objectives

Learning how to create and manipulate symbolic Variables


• Functions for creating symbolic variables.
• Defining functions with symbolic variables.
We will be looking into more advanced MatLab mathematical functions. Such as Differentiation and
integration We will be using the symbolic toolbox. This toolbox allows you to manipulate and compute
mathematical expressions that are frequently used in linear Algebra, Calculus, differential equations, and
other complicated fields.
In order to use this toolbox, we need to create as symbolic variables. We use the sym function and the
expression.

The sym function will return the expression in the rational form. And not in decimal format.
106 Chapter 7. Math Functions with Symbolic Data Types

The data type is of class sym, we can check that by use of the whos command.
Related to sym function, we have another function syms function. In this function, the symbolic
variables created are initialized to be themselves. Sounds confusing. Lets look at an example

In our example above, the value of a is a. It is itself.


syms a is the same as sym(′ a′ ).
Example, suppose we want to implement this function in MatLab

1+ 5
φ=
2
using the symbolic tool box.

We can use our function somewhere else

7.2 Differentiation and integration


Learning Objectives
Learning how to perform differentiation and integration
7.2 Differentiation and integration 107

• Differentiation
• High order differentiation
• Partial differentiation
• Integration
• Definite integral.

In this section, we will be using the symbolic variables to evaluate the differentiation and integration of
functions.

7.2.1 Differentiation

MatLab has the imensive power to calculate differentiation of simple to complicated functions. Lets create
a function f = sin (x)2 and calculate its differentiation in MatLab. We know, from Calculus that

d
( f ) = 2 cos (x) sin x
dx

If the equation, contains more than one variable, we can compute the partial derivatives as well.
Suppose we have f = sin x2 + cos y2 , calling our diff function with the function as the only argument, by
default, the function will compute the derivative with close proximity to x. Alternatively, you can mention
the additional argument, you want to differentiate with.
108 Chapter 7. Math Functions with Symbolic Data Types

7.2.2 Higher Order Differentiation


If we want to compute higher order derivatives, we use the function diff but in this case we supply some
additional argument parameters. A positive integer n. di f f ( f , x, n). The function f will be differentiated
to the nth order.

From the above example, we see that the nth derivative of f , is the (n − 1)th derivative. In simple terms,
the second derivative of function f is the derivative of the first derivative of f . So, for instance we can
also compute the second differentiation of function f using the following syntax.

1 >> diff(diff(f,x)) % The inner diff will evaluated ...


first, and the result evaluated by the outer diff
7.2 Differentiation and integration 109

7.2.3 Integration

To compute the integration of a function f is calculated by the help of the int function.

By variation of the argument parameters we provide, we can get different results.

Calling the int function with only one parameter, of course, the function, it will perform the integral of
the function, with respect to x if it exists, if it doesn’t, then it looks for y, if does not exist too, it performs
with respect to z.

You can add an additional argument parameter to the function. The second specifies what variable
you are interested to evaluate the integral with respect to.

int(S,v) is the indefinite integral of S with respect to v. v is a scalar SYM.

int(S,a,b) is the definite integral of S with respect to its symbolic variable from a to b. a and b are each
double or symbolic scalars. The integration interval can also be specified using a row or a column vector
with two elements, i.e., valid calls are also int(S,[a,b]) or int(S,[a b]) and int(S,[a;b]).

int(S,v,a,b) is the definite integral of S with respect to v from a to b. The integration interval can also
be specified using a row or a column vector with two elements, i.e., valid calls are also int(S,v,[a,b]) or
int(S,v,[a b]) and int(S,v,[a;b]).

int(...,’IgnoreAnalyticConstraints’,VAL) controls the level of mathematical rigor to use on the analyt-


ical constraints of the solution (branch cuts, division by zero, etc). The options for VAL are TRUE or
FALSE. Specify TRUE to relax the level of mathematical rigor in finding integrals. The default is FALSE.

int(...,’IgnoreSpecialCases’,VAL) controls how detailed answers are with respect to special parameter
values/ The options for VAL are TRUE or FALSE. Specify TRUE to ignore special cases of parameter
values. The default is FALSE.

int(...,’PrincipalValue’,VAL) is used to request a Cauchy principal value of a definite integral. (The


option is ignored for indefinite integration.) The possible values for VAL are TRUE and FALSE, the
default is FALSE.

int(...,’Hold’,VAL) returns a symbolic call to int, even if the result could be computed. Use RELEASE
on the result to undo this. The possible values for VAL are TRUE and FALSE, the default is FALSE.
110 Chapter 7. Math Functions with Symbolic Data Types

7.3 Solving Equations

Learning Objectives

Learning how to solve equations


• Solving equations with respect to a certain variable.
• Finding equation value at a certain point.
• Solving system of Equations.
• How to obtain coefficients of polynomials.
In this section, we will see how we can solve equations using the symbolic variables.
When defining equations, we use the double equal sign for the equals in the equation.
f = x3 + 6 ∗ x2 == 6 − 11 ∗ x.
When you use = it is an assignment operator. But == is an equality operator.
To solve the equation, we use the function solve and pass the function as the argument.
7.3 Solving Equations 111

By default, if your function contains more variable, the solve function will solve with respect to x, unless
you explicitly specify the variable, as a second argument in the solve function solve( f , y).

Lets solve some equations in Linear Algebra.

To solve the system of linear equation, we need to pass the three equations to the solve function. And lets
store the result
112 Chapter 7. Math Functions with Symbolic Data Types

Suppose we need to solve the equations and a certain point. We use the subs function which substitutes
the symbolic variable in the equation with the value passed.

We can also get the coefficients of the polynomials that are present in the function.
Suppose we have a function f 4 = 10x3 + 20x2 + 30x + 40. The coefficients are 10, 20, 30, 40. To get
this coefficients in MatLab, we use the sym2poly and pass our function as the argument parameter.
7.4 Symbolic Functions 113

If the function’s highest order is n, the sym2poly function will return n + 1 coefficients. If some are not
defined in the equation, they will be substituted with 0.

7.4 Symbolic Functions


Learning Objectives
Learning the use of symbolic functions
• Differentiation and integration with symbolic functions.
• Determining function values at a certain input.
In this section, we will how we can create symbolic functions and use them in differentiation,
integration and determining the function values at a certain point.

Note that the default for the second and third argument in the diff functions are 1 and x as we discussed in
the previous section.
114 Chapter 7. Math Functions with Symbolic Data Types

You can also perform integration. Take that as an exercise.


We can compute the values of the function for some given values of variable x and y. That is, how we
can compute the values of the function when we do a substitution for the variables. All we need to do is to
set the inputs of the function to appropriate values and it will compute the result for us.

To calculate the value of the function at a certain point, we substitute the variables with the number. For
example.
8. Interacting with MatLab Graphics

8.1 Basic Input Output

Learning Objectives

Learning basic input/output command


• Input numeric and string data.
• Displaying numeric and string output.
In this section we will look how we can store our data information into the MatLab software so that some
operations can be done on the data. And how to get the output of the data in different forms.
So far we have declaring our variables and values manually in the MatLab, but sometimes, we may be
interested in getting an input from a user. MatLab provides input function that prompts the user for an
input. This function has different forms, to specify what kind of an input to expect from the user.

We note that the second line does not start with the 2 greater signs in MatLab, this indicates that the
MatLab expects an input.
116 Chapter 8. Interacting with MatLab Graphics

We may however, be interested to get character values or strings from the user, in this case, we need
to add an additional argument parameter in the input function, ’s’, or "S", which tells the MatLab that the
input to be expected is a string,

If the user enters a numeric value, yet in our input function, we were expecting a character value, the
numeric value will be treated as a character array.
Sometimes, you may be interested to display an information to the user. We use the disp function and
pass the variable/information you want to display to the user.

8.2 More Input Output Commands


Learning Objectives
Learning more input/output commands
• Taking input in the form of a Menu
• fprintf function for formatting the style of the input.
In this section we will look into more functions to get the input from the user and to display information
to the user.
We may want to provide a list of choices for the user .
8.2 More Input Output Commands 117

menu Generate a menu of choices for user input.


CHOICE = menu(HEADER, ITEM1, ITEM2, ... ) displays the HEADER string followed in sequence by
the menu-item strings: ITEM1, ITEM2, ... ITEMn. Returns the number of the selected menu-item as
CHOICE, a scalar value. There is no limit to the number of menu items.
CHOICE = menu(HEADER, ITEMLIST) where ITEMLIST is a string, cell array is also a valid
syntax.
On most graphics terminals menu will display the menu-items as push buttons in a figure window,
otherwise they will be given as a numbered list in the command window (see example, below).
Example:

1 K = menu('Choose a color','Red','Blue','Green')
2 %creates a figure with buttons labeled 'Red', 'Blue' and ...
'Green'
3 %The button clicked by the user is returned as K (i.e. K ...
= 2
4 %implies that the user selected Blue).

A popup dialog will appear and expects you to choose an option. The value will stored to the variable will
be the position of the choice you selects. For example, in our case, we chooses ’C++’ so our CHOICE
variable will be equal to 1.

The fprintf function provides more options or ways to format our output as we display it.

We can specify the values format, such as an integer, double, float, string, etc. We can include escape
characters, we can print literal text.
118 Chapter 8. Interacting with MatLab Graphics

8.3 Plotting Data


Learning Objectives
Learning how to plot data
• Simple line plot using plot function.
• Setting title, xaxis, yaxis and other properties.
In this section, we will learn how we can make simple plots in MatLab. The plot function is used to make
plots. We can provide the arguments, containing the values we want to display.

In our example above, we have specify the values of x and y to be plotted by our function. You may decide
to plot the values of x only or y only, by specifying the variable x or y in the plot function.

In this case, every point of x in plotted against its position in the vector, such as 1 is plotted against 1, 3 is
plotted against 2, 5 is plotted against 3 etc.
Something else to note, if we are plotting x against y, then they must be of the same length.
8.3 Plotting Data 119

There are other customization that comes with the plot functions. For example, we may specify our
marker option, plot(x,y,'*')

100

90

80

70

60

50

40

30

20

10

0
1 2 3 4 5 6 7 8 9 10
120 Chapter 8. Interacting with MatLab Graphics

Check the documentation for the other options that can be specified to the plot function, such as title,
color, etc

8.4 3D Plots

Learning Objectives

Learning how to make 3D plots


• 3D line plot.
• 3D stem plot.
• Automatically generating 3D plots from workspace variables.
In this section, we will see how we can plot 3D plots, plots in three dimension. In the last section, we
plotted in 2D, two dimension.
To plot a 3D plot, we use the function plot3. We need to have three pieces of information to plot a 3D,
x axis, y axis and for z axis.
8.5 More on Plotting Options 121

You can make any plot based on your data from the workspace window without writing the code to
plot. In the workspace window, highlight the variables you need to plot, then head to the plot section
in the top bar and pick the option that suits you. Based on you data, you will see different options, for
instance, if you highlight three variables, the MatLab will assume you need to do a 3D plot, and options
for 3D will be available for you to pick one. Similarly if you selects 2 variables, then options to plot 2D
will be available.

8.5 More on Plotting Options


Learning Objectives
Learning more plot options
• Displaying multiple plots using figure.
122 Chapter 8. Interacting with MatLab Graphics

• Displaying multiple plots in a single figure using subplots.


• Generating code corresponding to a plot.

In this section, we will learn how to plot multiple plots in a single figure. Lets create some variables

1 x = rand(10,1);
2 y = rand(10,1);
3 z = rand(10,1);

When we call the plot function, it will display each plot at a time. The newer plot function call will
overwrite the previous plot. For example

1 plot(x,y);
2 plot(x,z);

Only the plot plot(x, z) will be displayed in our output.

When we plot plot(x, y), we get the following

But when we plot (x, z), it is replaced ,


8.5 More on Plotting Options 123

We may be interested to have the two plots separately and view them. To achieve this, we use the
reserved keyword figure, just before calling the second plot. This will tell the MatLab to create a new
figure, with the specified plot, retaining the first plot.

Sometimes, it is necessary to have the different plots in the same figure. To achieve this, we need to
use the subplot function. This function needs three pieces of information. The number of subplots you
want to have in your figure. subplot(2,2) means the we divide our plot area into 2 rows by 2 columns.
Next we need to mention a number that indicates the position of the x-axis. subplot(2,2,1) will mean
that we are going to plot the first plot which is the first row and first column plot. The plots in the figure
124 Chapter 8. Interacting with MatLab Graphics

are numbered in a row wise fashion. for our case


 
1 2
3 4

Next we need to specify the plot that is to be plotted in that specific area.

The MatLab software also provides easier way to plot functions without writing the code. In this
particular case, all you need is to plot(x,y) and go to the Property Editor settings. You can make changes
as it pleases you and more customization. Then you can generate the code and use it in your program, or
customize to plot other plots.
8.6 Bar Graphs 125

The code is generated for you

1 function createfigure(X1, Y1)


2 %CREATEFIGURE(X1, Y1)
3 % X1: vector of x data
4 % Y1: vector of y data
5
6 % Auto−generated by MATLAB on 30−Aug−2022 18:24:05
7
8 % Create figure
9 figure1 = figure;
10
11 % Create axes
12 axes1 = axes('Parent',figure1);
13 hold(axes1,'on');
14
15 % Create plot
16 plot(X1,Y1);
17
18 % Create ylabel
19 ylabel('y−axis');
20
21 % Create xlabel
22 xlabel('x−axis');
23
24 % Create title
25 title('Graph of x against y');
26
27 grid(axes1,'on');
28 hold(axes1,'off');
29 % Set the remaining axes properties
30 set(axes1,'Color',[1 1 0],'XColor',[1 0 0],'YColor',[1 0 0],'ZColor',...
31 [1 0 0]);

8.6 Bar Graphs

Learning Objectives

Learning Bar Graphs and Its different variants

• Simple bar Graphs


• Vertical Bar Graphs
• Stacked Bar Graphs
• Grouped Bar Graphs

The bar function is used to create bar graphs. Suppose we have some data y = [ 20 25 30 50 90
80], calling our function will plot a simple bar graph.
126 Chapter 8. Interacting with MatLab Graphics

You can provide the data for the x axis as well. By default, the x-axis will have the entry numbers for the
data in the y axis as seen in the above example.
8.6 Bar Graphs 127

You may want to control the width size of the bar graphs, in that case, we provide an additional argument
parameter in our bar function. bar(x, y, 0.4). The width is inform of a decimal value, from 0-1

In the case where the data contains several rows, the bar function plots the rows differently in the
same figure.
128 Chapter 8. Interacting with MatLab Graphics

We may want it as a Stacked bar graph and not different individual graphs. To do that, we provide another
argument parameter.

The function barh plots the bars horizontally as opposed to the vertical fashion of the bar function.
8.7 Combining Plots 129

8.7 Combining Plots


Learning Objectives
Learning how to combine plots
• Combining plots into the same figure using the hold on.
In this section, we are going to look at a useful technique to combine multiple plots in the same figure. In
the last section, we saw how we could create multiple plots in different figures. In this section, we are
going to see how we can create multiple plots in the same figure.
We are going to use a command hold on that will tell the MatLab not to create a new figure when we
want to plot another plot. But it will plot the new plot on the same figure.

In the above example, after we have plotted the f (x) = sin(x), plotting again the f (x) = cos(x) does not
create a new figure, but plots on the same figure. We have added the legends to show the different plots.
You can set off the hold on option and this will plot the latest figure.
We can be interested to plot multiple but different types of plots into the same figure. For example,
you may want to plot the line plot and the scatter plot together in the same figure. The hold on option
allows this functionality to take place.
130 Chapter 8. Interacting with MatLab Graphics

Its important after you are done with hold on, to set it to off so that to avoid confusion in other
following plots, should you have others.

8.8 Brush Tool for Plots

Learning Objectives

Learning the use of brush tool

• Visual analysis of the data with the brush tool.


• Outlier removal with the brush tool.

In this section, we are going to look how we can interact with the data that we have already plotted and
how we can modify it.

You may have outliers in your data, for example, in our example below, we have two outliers, we can
use the brush option in the figure created, when we plot, and we can modify, either remove this outliers,
replace them with a constant, remove all others but this, etc, the options are shown when you right click
your mouse after selecting the outliers.
8.9 Plots with two Y-Axis 131

For instance, we may decide to remove the outliers, and our plot will be updated without the outliers. You
may try the other options.

8.9 Plots with two Y-Axis


Learning Objectives
Learning how to create plots with two Y-axis
• Creating plots with two y-axis scales corresponding to two different variable.
Consider the following data

1 >> monthnum = 1:12;


132 Chapter 8. Interacting with MatLab Graphics

2 >> pecip = [3.4 3.3 4.3 3.7 3.5 3.7 3.4 3.4 3.4 3.9 4.0 3.8];
3 >> temp = [ 16 25 40 48 59 70 77 77 65 56 47 34];
4 >>

We want to have a plot where on the y-axis we want to have a plot of month versus pecip and on the other
y-axis we want to have a plot of months versus temperatures. This means that at one side of the y axis,
such as the left side of the y axis , we ant to have a scale of precipitation and the other side of the y-axis,
the right hand side of the y axis, we want to have a scale of temperature .
The matlab command yyaxis can be used to achieve this. We specify the left or right .

8.10 Animated Line

Learning Objectives

Learning how to create animated lines


• Animated lines using the animated function.
• Controlling the speed of drawing the line.
To create animated lines, we use the built in function animatedline.
8.11 Existence of Scripts, files, folders, etc 133

Run the following code in your MatLab IDE and you will visualize the animation.

1 h = animatedline;
2 x = 1:250;
3 y = sin(x);
4 for k = 1:length(x)
5 addpoints(h,x(k),y(k));
6 drawnow
7 end

8.11 Existence of Scripts, files, folders, etc


Learning Objectives
Learning the use of exist function to check for existence of
• Files
• Scripts
• Folders
• Functions
In this section, we will focus on the exist function. This function can be used to check the existence of
files, scripts, functions, folders, variables, etc .
The syntax is exist namecheck
This function has a number of outputs, of which each one of them has a different meaning.
The exist(NAME) returns
0 if NAME does not exist
1 if NAME is a variable in the workspace
2 if NAME is a file with extension .m, .mlx, .mlapp, or .sfx, or NAME is the name of a file with a
non-registered file extension (.mat, .fig, .txt).
3 if NAME is a MEX-file on the MATLAB search path
4 if NAME is a Simulink model or library file on the MATLAB search path
5 if NAME is a built-in MATLAB function. This does not include classes
6 if NAME is a P-code file on the MATLAB search path
7 if NAME is a folder
8 if NAME is a class (exist returns 0 for Java classes if you start MATLAB with the -nojvm option.)
There are also other options that can be used to specify what type of a file we are looking for.
134 Chapter 8. Interacting with MatLab Graphics

exist(’NAME’,’builtin’) checks only for built-in functions.


exist(’NAME’,’class’) checks only for classes.
exist(’NAME’,’dir’) checks only for folders.
exist(’NAME’,’file’) checks for files or folders.
exist(’NAME’,’var’) checks only for variables.

NAME can include a partial path, but must be in a folder on the search path, or in the current folder.
Otherwise, name must include a full path.
If NAME specifies a file with a non-registered file extension (.mat, .fig, .txt), include the extension.
NAME is case insensitive on Windows systems, and case sensitive for files and folder on UNIX
systems.
MATLAB does not examine the contents or internal structure of a file and relies solely on the file
extension for classification.

8.12 Directory Manipulation


Learning Objectives
Learning director manipulation functions
• Displaying the files in the current working folder.
• Displaying files with specific extensions only
• Displaying files with specific names.
• Going up and down in a directory hierarchy.
• Changing current working directory or folder.
• Removing a certain directory or folder.
• Returning MatLab related files with what function.
8.12 Directory Manipulation 135

In this section, we are going to look at some of the functions to manipulate the directories in MatLab.
The dir function is used to list all the contents of the current folder, if no additional argument is
provided. The ls function is used to achieve the same functionality as well.

With an argument, which is supposedly to be a folder, the MatLab will list the contents of that specified
folder or path.
There are a number of options that comes with this functions. We may decide to list only the files in
the directory that has an .bat extension.

We may also be interested to check for .bat files in the current directory all the way to all the sub
directories of the current directory.
136 Chapter 8. Interacting with MatLab Graphics

Let us look at some of more options to the function.

dir *f.m - means, list all the files that ends with the letter f and has an extension of .m

dir *f*.m - means, list all the files that has an f any position and has the extension .m

You can also mention some REGEX in the dir function. This are regular expressions that checks for
some pattern in the data.

The cd function is also helpful when navigating up and dowm levels of directories.

Its an acronym for change direcftory

cd Change current working directory.


cd directory-spec sets the current directory to the one specified.
cd .. moves to the directory above the current one.
cd, by itself, prints out the current directory.

WD = cd returns the current directory as a character vector.

Use the functional form of cd, such as cd(’directory-spec’), when the directory specification is stored
as text.

The mkdir function is used to create folders or directories in Matlab. You can specify what place or
location you want to create your folder or directory in. By default, it will create a new folder in the current
directory.

The rmdir function will remove an empty directory.


8.12 Directory Manipulation 137

To forcefully remove directories with contents, we use the rmdir function as a function and not a
command, meaning we are going to provide some argument parameters.

The movefile function is used to move files and folders from one location to another.
138 Chapter 8. Interacting with MatLab Graphics

In the above example, we have moved folder EX2 from its parent Folder EX1 to our current directory.
The what function or command, returns the files that are associated with MatLab.

8.13 Textual Processing


Learning Objectives
Learning text processing functions and operations
• Reading a file
• Splitting text into lines.
8.13 Textual Processing 139

• Removing empty lines.


• Obtaining the individual words.
• Creating frequency counts for the words.
In this section, we will kook at some text processing functions that MatLab provides. We will be reading
a text file from our computer and try to do some textual processing in MatLab environment.
fileread is used to read a file, the parameter argument is the file name.
Let us consider the example below. The file waebra.txt is read into variable text and we note that
it is of character array, the text variable.

We can perform some useful operations, for example, we may convert the text into a string variable,

We may use splitlines function to split the text into arrays of lines.
140 Chapter 8. Interacting with MatLab Graphics

We may want to get rid of the empty linees.

1 TF = (text == ''); % CHECKING THE EMPTY LINES


2 text(TF) = []; % NOW TEXT HAS NO EMPTY LINES.
3 % TO GET RID OF SOME CHARACTERS.
4 p = {',','?','!','.'}; % STORING THE CHARACTERS WE WANT TO REPLACE
5 text = replace(text,p,' '); REPLACING THE CHARACTERS ABOVE WITH AN EMPTY ...
STRING, A SIGNLE SPACE
6 % TO GET RID OF TRAILING SPACES, WE USE THE STRIP FUNCTIONS
7 text = strip(text);
8 % RETRIVE THE COUNT OF INDIVIDUAL WORDS. FIRST MAKE THE TEXT A ONE BIG STRING
9 text = join(text);
10 % NOW SPLIT THE TEXT into individual WORDS.
11 text = split(text);
12 % WE CAN USE THE TABULATE FUNCTION TO GET THE STATISTICS OF WORDS
13 x = tabulate(text);

Practice the above examples in your MatLab IDE

8.14 Project Exercise 1


• Consider the file named project1.txt

1 from: mathew <[email protected]>


2 subject: alt.atheism faq: atheist resources
3 summary: books, addresses, music −− anything related to atheism
4 keywords: faq, atheism, books, music, fiction, addresses, contacts
5 distribution: world
6 organization: mantis consultants, cambridge. uk.
7 archive−name: atheism/resources
8 alt−atheism−archive−name: resources
9 last−modified: december
10 version:
11 atheist resources
12 addresses of atheist organizations
13 usa
14 freedom from religion foundation
15 darwin fish bumper stickers and assorted other atheist ...
paraphernalia are
16 available from the freedom from religion foundation in the us.
8.14 Project Exercise 1 141

17 write to: ffrf


18 evolution designs
19 evolution designs sell the "darwin fish". it's a fish symbol, ...
like the ones
20 christians stick on their cars, but with feet and the word ...
"darwin" written
21 inside. the deluxe moulded 3d plastic fish is postpaid in the us.
22 write to: evolution designs, laurel canyon , north hollywood,
23 ca 91605.
24 people in the san francisco bay area can get darwin fish from ...
lynn gold.
25 for net people who go to lynn directly, the
26 price is per fish.
27 american atheist press
28 aap publish various atheist books −− critiques of the bible, ...
lists of
29 biblical contradictions, and so on. one such book is:
30 "the bible handbook" by w.p. ball and g.w. foote. american ...
atheist press.
31 absurdities, atrocities, immoralities... contains ball, foote: ...
"the bible
32 contradicts itself", aap. based on the king james version of the ...
bible.
33 an alternate address (which may be newer or older) is:
34 african−americans for humanism
35 an organization promoting black secular humanism and uncovering ...
the history of
36 black freethought. they publish a quarterly newsletter, aah ...
examiner.

Save the file in your computer.


2. Replace the special characters ’.’, ’,’, ’:’, ’/’,’"’, ’"’ that are present in the text file using a space
character. You will need to convert it into the string first for this purpose using the string() function
3. Next, break the string into individual words.
4. Find the frequencies of the words in the text file.
5. Find a sorted list of words in descending order based on their respective frequencies.
6. Create a bar plot of the top 10 most frequently occurring words. On the x-axis we expect the names
of the words and on the y-axis we should have the percentage frequencies of the words. (Note:
please note that the tabulate() may return a cell array. Cell data type is covered in the later portion of
the course. But for now you need to know that when applying the bar() function, the first argument
which is in this case is cell needs to be converted to categorical which you can do by calling a
function categorical() and the second argument needs to be in numeric format so for that you can
convert the cell to numeric of matrix by calling the function cell2mat()). The final output should be
something like this
142 Chapter 8. Interacting with MatLab Graphics
9. Importing Data into MatLab

9.1 Importing data from Excel

Learning Objectives

Learning how to import excel files into matlab

• Learning the import data tool.

This section, we look how we can import data into Matlab environment and perform some operations to
the data.

There is an import data feature that is at the top bar of the MatLab IDE that allows you to import your
data.
144 Chapter 9. Importing Data into MatLab

You can make selection of the data you are interested to import.

Now the data is imported and can be seen in the workspace

9.2 Importing data in Different Formats


Learning Objectives
Learning how to import data in different formats
• Reading files with any type of delimiter type.
9.2 Importing data in Different Formats 145

• The dlmread() function.


The previous section, we imported excel data format. In this section, we are going to look at how we
can import data of different formats Such as csv, comma separated value. To import this, the data must be
in numeric format. We use the csvread and pass the argument parameter of the file name.

This function is limited only to .csv files.


There is a more general function that can read different formats of the file.
Lets read a file that has a space as the separator. The dmlread function, takes the first argument as the
file name and the second argument as the delimiter.

If our file has different delimiter, for instance ’b’ is our delimiter in our next example.
146 Chapter 9. Importing Data into MatLab

9.3 Practice Exercise


1. Write a MATLAB script that will change the words in string such that the words appear in reverse
order. Assume that that the only characters in the input string are letters and spaces. For instance. If
the user input = ’Will the ecological jail rule outside the tear’; than the output should be output =
’tear the outside rule jail ecological the Will’.
2. In this example we are going to do some processing on a data file and then will store the results in a
specific folder. Do the following steps to complete this assignment.
1. Download the file data.txt and save it on your computer.
2. Read this file into the MATLAB environment.
3. Write statements that will only select the rows from the data where the second column has greater
than or 3 value. This will result in reduced rows.
4. Next check if the working directory has a folder named Results.
5. If yes go to that directory and store reduced data (reduced rows) in csv format in that folder
under the name, reduced data.csv
6. Else create a folder with the name results in the working folder and store the reduce data in that
folder under the name reduced data.csv

data.csv

1 2.5,3.5,1.4,0.2
2 4.9,3,1.4,0.2
3 4.7,3.2,1.3,0.2
4 4.6,3.1,1.5,0.2
5 5,3.6,1.4,0.2
6 5.4,3.9,1.7,0.4
7 4.6,3.4,1.4,0.3
8 5,3.4,1.5,0.2
9 4.4,2.9,1.4,0.2
10 4.9,3.1,1.5,0.1
11 5.4,3.7,1.5,0.2
12 4.8,3.4,1.6,0.2
13 4.8,3,1.4,0.1
9.3 Practice Exercise 147

14 4.3,3,1.1,0.1
15 5.8,4,1.2,0.2
16 5.7,4.4,1.5,0.4
17 5.4,3.9,1.3,0.4
18 5.1,3.5,1.4,0.3
19 5.7,3.8,1.7,0.3
20 5.1,3.8,1.5,0.3
21 5.4,3.4,1.7,0.2
22 5.1,3.7,1.5,0.4
23 4.6,3.6,1,0.2
24 5.1,3.3,1.7,0.5
25 4.8,3.4,1.9,0.2
26 5,3,1.6,0.2
27 5,3.4,1.6,0.4
28 5.2,3.5,1.5,0.2
29 5.2,3.4,1.4,0.2
30 4.7,3.2,1.6,0.2
31 4.8,3.1,1.6,0.2
32 5.4,3.4,1.5,0.4
33 5.2,4.1,1.5,0.1
34 5.5,4.2,1.4,0.2
35 4.9,3.1,1.5,0.1
36 5,3.2,1.2,0.2
37 5.5,3.5,1.3,0.2
38 4.9,3.1,1.5,0.1
39 4.4,3,1.3,0.2
40 5.1,3.4,1.5,0.2
41 5,3.5,1.3,0.3
42 4.5,2.3,1.3,0.3
43 4.4,3.2,1.3,0.2
44 5,3.5,1.6,0.6
45 5.1,3.8,1.9,0.4
46 4.8,3,1.4,0.3
47 5.1,3.8,1.6,0.2
48 4.6,3.2,1.4,0.2
49 5.3,3.7,1.5,0.2
50 5,3.3,1.4,0.2
51 7,3.2,4.7,1.4
52 6.4,3.2,4.5,1.5
53 6.9,3.1,4.9,1.5
54 5.5,2.3,4,1.3
55 6.5,2.8,4.6,1.5
56 5.7,2.8,4.5,1.3
57 6.3,3.3,4.7,1.6
58 4.9,2.4,3.3,1
59 6.6,2.9,4.6,1.3
60 5.2,2.7,3.9,1.4
61 5,2,3.5,1
62 5.9,3,4.2,1.5
63 6,2.2,4,1
64 6.1,2.9,4.7,1.4
65 5.6,2.9,3.6,1.3
66 6.7,3.1,4.4,1.4
67 5.6,3,4.5,1.5
68 5.8,2.7,4.1,1
69 6.2,2.2,4.5,1.5
70 5.6,2.5,3.9,1.1
71 5.9,3.2,4.8,1.8
72 6.1,2.8,4,1.3
73 6.3,2.5,4.9,1.5
74 6.1,2.8,4.7,1.2
148 Chapter 9. Importing Data into MatLab

75 6.4,2.9,4.3,1.3
76 6.6,3,4.4,1.4
77 6.8,2.8,4.8,1.4
78 6.7,3,5,1.7
79 6,2.9,4.5,1.5
80 5.7,2.6,3.5,1
81 5.5,2.4,3.8,1.1
82 5.5,2.4,3.7,1
83 5.8,2.7,3.9,1.2
84 6,2.7,5.1,1.6
85 5.4,3,4.5,1.5
86 6,3.4,4.5,1.6
87 6.7,3.1,4.7,1.5
88 6.3,2.3,4.4,1.3
89 5.6,3,4.1,1.3
90 5.5,2.5,4,1.3
91 5.5,2.6,4.4,1.2
92 6.1,3,4.6,1.4
93 5.8,2.6,4,1.2
94 5,2.3,3.3,1
95 5.6,2.7,4.2,1.3
96 5.7,3,4.2,1.2
97 5.7,2.9,4.2,1.3
98 6.2,2.9,4.3,1.3
99 5.1,2.5,3,1.1
100 5.7,2.8,4.1,1.3
101 6.3,3.3,6,2.5
102 5.8,2.7,5.1,1.9
103 7.1,3,5.9,2.1
104 6.3,2.9,5.6,1.8
105 6.5,3,5.8,2.2
106 7.6,3,6.6,2.1
107 4.9,2.5,4.5,1.7
108 7.3,2.9,6.3,1.8
109 6.7,2.5,5.8,1.8
110 7.2,3.6,6.1,2.5
111 6.5,3.2,5.1,2
112 6.4,2.7,5.3,1.9
113 6.8,3,5.5,2.1
114 5.7,2.5,5,2
115 5.8,2.8,5.1,2.4
116 6.4,3.2,5.3,2.3
117 6.5,3,5.5,1.8
118 7.7,3.8,6.7,2.2
119 7.7,2.6,6.9,2.3
120 6,2.2,5,1.5
121 6.9,3.2,5.7,2.3
122 5.6,2.8,4.9,2
123 7.7,2.8,6.7,2
124 6.3,2.7,4.9,1.8
125 6.7,3.3,5.7,2.1
126 7.2,3.2,6,1.8
127 6.2,2.8,4.8,1.8
128 6.1,3,4.9,1.8
129 6.4,2.8,5.6,2.1
130 7.2,3,5.8,1.6
131 7.4,2.8,6.1,1.9
132 7.9,3.8,6.4,2
133 6.4,2.8,5.6,2.2
134 6.3,2.8,5.1,1.5
135 6.1,2.6,5.6,1.4
9.3 Practice Exercise 149

136 7.7,3,6.1,2.3
137 6.3,3.4,5.6,2.4
138 6.4,3.1,5.5,1.8
139 6,3,4.8,1.8
140 6.9,3.1,5.4,2.1
141 6.7,3.1,5.6,2.4
142 6.9,3.1,5.1,2.3
143 5.8,2.7,5.1,1.9
144 6.8,3.2,5.9,2.3
145 6.7,3.3,5.7,2.5
146 6.7,3,5.2,2.3
147 6.3,2.5,5,1.9
148 6.5,3,5.2,2
149 6.2,3.4,5.4,2.3
150 5.9,3,5.1,1.8

Check Solutions 13.5


10. MatLab Programming

10.1 Conditional If Statement


Learning Objectives
Learning How to use conditional if statement
• Making branches of code to execute based on some conditions.
• If elseif programming construct
• Understanding with a simple student marking example.
The if statement is used to check for a certain condition. You may be having a code such that at some
point, you have to perform different operations depending on the conditions.

The else condition.


152 Chapter 10. MatLab Programming

The elseif allows one to check for multiple conditions in series, i.e., check for first condition, if its not
the case, proceed to the next condition, etc.
Consider the example below, we ask the user for their marks and print the Grade according to the
marks obtained.

10.2 Continue Statement


Learning Objectives
Learning the concepts of skipping up a certain iterations of a loop
• The continue programming statement.
• Skipping one iteration of a loop.
The continue statement is used to skip a single iteration of a loop upon a certain met condition.
Consider a case where some students missed an examination, maybe because they had health issues,
and the instructor is a bit sympathetic and instead of giving them a zero, he do not want to write the data
for those students, and most probably would prefer to give them a retake.
10.3 For Loops 153

Try the above example in your MatLab ide.

10.3 For Loops


Learning Objectives
Learning For loops
• Iterating through a piece of code with FOR loops
• Understanding with a simple student grading example.
A for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute
a specific number of times.
The syntax of a for loop in MATLAB is:

1 for index = values


2 <program statements>
3 ...
4 end

An example

A more advanced for loop example


154 Chapter 10. MatLab Programming

10.4 Nested For Loops


Learning Objectives
Learning nested For loops
• Loop containing another loop
• Understanding with a simple student grading example.
A nested for loop is a for loop withing anothere for loop.
Example

A more advanced example

Input
10.5 While Loops 155

10.5 While Loops


Learning Objectives
Learning WHILE loops
• WHILE loop motivation and syntax
• Stopping an execution of the WHILE LOOP
• Understanding with a simple student grading example.
One of the major differences between a for loop and a while loop, is that in the for loop we need to
know the exact number of times there will be iterations, but for a while loop, we just need to check the
condition and there will be iterations as long as the condition holds.

To use the while loop, we need to use the reserved key word while and followed by a condition and ends
with the keyword end

1 while <condition>
2 Code here
3 end

Similarly, we can have nested while loops.

10.6 Break Statement


Learning Objectives
Learning the concepts of breaking up the iterations of a loop
156 Chapter 10. MatLab Programming

• The break programming statement


• Terminating a loop before the final condition of a loop.
The break statement terminates the loop at a certain point. This tells MatLab to totally halt the
iterations and proceed to the next code segments, if any.

10.7 Switch Statement


Learning Objectives

Learning how to make choices with Switch statement


• Choices in numeric form
• Choices in character form
Consider the following examples

Switch in character values


10.8 Pracitce Exercise 4 157

We can also use {} to check for multiple choices

10.8 Pracitce Exercise 4


1 Write a program that will print the stars in format given below

2. Given n (always odd), return output a that has concentric rings of the numbers 1 through (n+1)/2
around the center point. For instance, if n = 5, we will have the following matrix.
158 Chapter 10. MatLab Programming

3. The Goldbach conjecture asserts that every even integer greater than 2 can be expressed as the sum
of two primes. Write a script that will accept an even integer and then it will return primes p1 and
p2 that satisfy the condition n = p1 + p2. Note that the primes are not always unique. The program
should just return one such combination of the primes.
4. Given a positive integer n taken from the user, your program should create an n-by-n matrix in
which the integers from 1 to n2 wind back and forth along the rows as shown in the examples below.

5. Write a MATLAB script that will accept an array of numeric values from the user and then return a
statement ’monotonically increasing’ if the elements of the input array increases monotonically
(i.e. each element is larger than the previous). Otherwise return a statement stating that it is ’not
monotonically increasing’.
6. Write a MATLAB script that will accept an integer value N from the user and then it will create a
matrix A of alternating ones and zeros of the same size. For instance if the user enter 5 than it will
create
11. Creating Functions

11.1 Functions
Learning Objectives
Learning Learning custome built functions
• Custom built functions with no inputs and outputs
• A simple print function
Basic syntax of a function

1 function_name(argument1,argument2,\dots,argumentn)

Depending with the outputs and inputs, there can be may various types of functions.
There are functions that taks no input parameters and does not print out anything . Example

1 function print_function()
2 disp("Hello Hello Kenya! ")
3 end

We need to save the function with the same filename as the function name. that is print function.m
Now we can call our funciton anywhere, either inside a script or even at the command window.

11.2 Functions with Inputs


Learning Objectives
Learning functions with inputs
160 Chapter 11. Creating Functions

• Passing inputs to a function


• The concept of local and global variables
• A simple funciton for computing square.
In this section, we will look at functions that takes inputs .
It is recommended always to give meaningful names to functions.
Lets create a simple funciton that calculates the square of a number and print the answer.

Lets note that the variable x inside the function, is only locally available inside the square... function
environment. We use the term, local variable. Meaning x is a local variable for the funtion.
If you need the variable to be available outside the function, you may use the keyword global. Although
it is not a good programming practice.

11.3 Functions with Inputs and Outputs


Learning Objectives
Learning how to create funcitons with inputs and outputs
• Functions with multiple inputs and outputs
• An example funciton for computing statistical measures of data.
In this section, we will be looking at functions with multiple inputs and outputs.
For example, consider the following code
11.4 Return Statement 161

In the above function, we create a funciton that takes two matrices as inputs, then it concatenates them, it
calculates the standard deviation, variance, minmum value and maximum values, and then returns the
results.

11.4 Return Statement


Learning Objectives
Learning the use of return statement
• Returning the control from a funcntion to a place in a code from where it is called.
• An example of summation for learning the concept.
In this section, we will learn the use of the return statement which is mostly used inside the definition of a
funciton.
Consider the following example.
In the example, lets compute the sum of the numbers from 0 to the ntered number N

The return statement is used to exit the function and transfer the control to the point in the code from
where the it was called, this means that irrespective of whether you put this inside of a for loop, while
loop or a nested loop, it is going to skip all the code that comes after this return statement in the function.
It is going to exit the function and it will pass the control to the line of code where it has been called.
12. Sharing MatLab Results

12.1 Sharing Results

Learning Objectives

Sharing results, code with others


• Publishing your code and results in different formats for sharing with others.
• Making section in the code.
• Publishing Your code, results using live editor.
• Including images, equations and others.
In this section we will learn how you can share your MatLab results and code in MatLab.
The first thing is to write your code. It is recommended that you label your parts/sections of the code
properly to aid the MatLab in making a documentation for your code.

After that, you need to publish your results. Click the publish ttab in the MatLab IDE top bar. Then click
the publish button.
164 Chapter 12. Sharing MatLab Results

The results are well documented in an html format. You can specify the format you are interested in, y
editing the publish configurations

The other way to share your results, is by the aid of the live script option. A live script allows one to
generate report, you can run your code without necessarily saving it.
You can add texts, equations, images, etc in your code.
12.1 Sharing Results 165

You can now export your code plus results to any format you choose.
166 Chapter 12. Sharing MatLab Results

Similarly, you can add equations.


13. Solutions to Practice Exercises

13.1 Solutions to Practice Exercise 5.12

1
1 A = [1 0 0 0; 0 1 0 0; 1 1 1 0];
2 [most_money, person] = max((A(:,1)*0.25) + ...
(A(:,2)* 0.1) + (A(:,3)*0.05) +
3 (A(:,4)* 0.01));

1 F = ((9 / 5) * C) + 32;
2 C = (F − 32) * (5/9);

23
1 mean(A .* B)

1 isempty(intersect(A, B))

45
1 sum(A .* B)

13.2 Solution to Practice Exercise 6.14


1. find (Q>0)
2. X(end:-1:1)
3. X(1:2:end)
4. R = A(6:end, 6:end)
5. unique(A( A>= 2 & A<= 5))

6.
1 T = tabulate(A);
2 [a, b] = sort(T(:,3),'descend');
3 T(b,:)
168 Chapter 13. Solutions to Practice Exercises

7. A = A(find(A))

8.
1 A = randperm(100,10)
2 A1 = length(A(A ≤ 25))
3 A2 = length(A(A>25 & A ≤ 75))
4 A3 = length(A(A>75 & A ≤ 100))

9. sort(char(X))
we convert into char because sort(X) will treat X as a single % element whereas we want to extract
individual characters from X

10.
1 [number_of_zeros ,row_with_max_non_zeors] = ...
min(sum(ismember(a(1:end,:),0),2))
2 \% the variable row_with_max_zeros contains the ...
answe

13.3 Solution to Practice Exercise 6.15

1.
1 R = [A(1,1) , A(1,end) ; A(end,1), A(end,end)]

1 X == char(X); % this converts X into ...


character array
2 isequal(X,X(end:−1:1))

3.
2.
1 A = rand(5);
2 A(3,:) = []

Note 1: Please note that this syntax cannot be used to delete individual elements. The resultant
matrix should have the same number of row elements corresponding to all columns and the same
number of column elements corresponding to all rows.
Note 2: This was not covered in video lectures, so you learned something new

4.
1 10.1. a+b −> Correct statement
2 10.2. a*b −> Incorrect statement
3 10.3. a.*b −> Correct statement
4 10.4. A*b −> Correct statement
5 10.5. A.*b −> correct statement
6 10.6. a'*b −> Correct statement
7 10.7. a*b' −> Correct statement
8 10.8. A*A −> Correct statement
9 10.9. A.*A −> Correct statement
10 10.10. A*B −> Correct statement
11 10.11. A.*B −> Incorrect statement
12 10.12. B*A −> Incorrect statement
13 10.13. B*B−> Incorrect statement

1 max_length = max([length(A), length(B),length(C)]);


2 x = zeros(3,max_length);
13.4 Solution to Project Exercise 1 169

3 x(1,max_length−length(A)+1:max_length) = A;
4 x(2,max_length−length(B)+1:max_length) = B;
5 x(3,max_length−length(C)+1:max_length) = C;

5. A = [1:7; 9:-2:-3; 2.∧ (2:8)]


6.
7. It will return the third row of A
8. It will interchange row 2 with row 3.

13.4 Solution to Project Exercise 1

1 %Step 1:
2 file = fileread('PATHTOYOURFILE/project1.txt');
3 %Step 2:
4 file = string(file);
5 p = {'.', ',', ':', '/','"', '"'};
6 file = replace(file,p,' ');
7 %Step 3:
8 file = split(file);
9 %Step 4:
10 frequencies = tabulate(file);
11 %Step 5:
12 [freq, index] = sort(cell2mat(frequencies(:,3)),'descend');
13 %Step 6:
14 bar(categorical(frequencies(index(1:10),1)),cell2mat(frequencies(index(1:10
15 3)))

13.5 Solution to Practice Exercise 9.3


1.

1 clear all
2 input = "HELLO MAN HOW ARE YOU AND HOW ARE YOU DOING";
3 output = split(input);
4 output = output(end:−1:1);
5 output = join(output);
6 fprintf('The input string was \n"%s"\n \n \n', input);
7 fprintf('The corresponding output is \n "%s" \n',output);

2.

1 X = csvread('C:\data.csv');
2 Y = X(:,2) > 3.0;
3 Z = X(Y,:);
4 if exist('Results') == 7
5 csvwrite('Results\reduced_data.csv',Z);
6 else
7 mkdir Results
8 csvwrite('Results\reduced_data.csv',Z);
9
10 end
170 Chapter 13. Solutions to Practice Exercises

13.6 Solutions to practice exercise 10.8

1.
1 for i=1:2:9
2 for j=1:i
3 fprintf('*')
4 end
5 fprintf('\n')
6 end
7
8 for i=9:−2:1
9 for j=i:−1:1
10 fprintf('*')
11 end
12 fprintf('\n')
13 end

1 n = input('Enter a number');
2 A = zeros(n);
3 m = (n+1)/2;
4 for i=1:m
5 A(i:end−i+1,i) = (m−i) +1;
6 A(i,i:(end−i+1)) = (m−i) +1;
7 A(i:(end−i+1),end−i+1) = (m−i) +1;
8 A(end−i+1, i:end−i+1) = (m−i) +1;
9 end
10 disp('The bullseys matrix is');
11 A

3.
2.
1 n = input('Enter an even number greater than 2\n');
2 p = primes(n);
3 flag = 0;
4 for i=1:length(p)
5 for j =1:length(p)
6 if p(i)+ p(j) == n
7 flag = 1;
8 fprintf('The two prime number are %d and %d \n',p(i),p(j));
9 break;
10 end
11 end
12 if(flag==1)
13 break;
14 end
15 end

1 n = input('Enter a number n\n');


2 A = zeros(n);
3 for i=1:n
4 if rem(i,2) ̸= 0
5 A(i,:) =(((n*i)−n)+1):1:n*i;
6 else
7 A(i,:)= n*i:−1:((n*i)−(n−1));
8 end
9 end
10 A
13.6 Solutions to practice exercise 10.8 171

5.
4.
1 A = input('Enter a numerical vector array in the form [5 8 9 8 7] \n');
2 for i=2:length(A)
3 if A(i) > A(i−1)
4 flag = 0;
5 else
6 flag = 1;
7 disp('Not monotonically increasing');
8 break;
9 end
10 end
11 if flag ==0
12 disp('Monotonically increasing');
13 end

1 n = input('Enter the size of the matrix');


2 x = zeros(n);
3 for i=1:n
4 if rem(i,2)== 0
5 x(i,1:2:end) = 1;
6 else
7 x(i,2:2:end) = 1;
8 end
9
10 end
172 Chapter 13. Solutions to Practice Exercises

6. –END–

You might also like