Matlab Tutorials
Matlab Tutorials
Lecturer:
Vincent Mwai
Contents
1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
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
• Command window
• Workspace
• Current folder
• Various tabs
In this section we are going to look at the key graphical interface components of the MATLAB software.
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
In the command window, we can perform some operations, for instance, addition, Subtraction,
multiplication, division, integration and so on
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.
This particular bar shows the directory location of the folder which is called the current folder.
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.
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
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
a = 16
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.
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
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
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.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.
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
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
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
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,
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
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
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
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
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
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
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
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
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.
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.
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
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.
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
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.
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.
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.
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.
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,'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]
1 >> a = [5 8 9; 8 7 9; 1 9 3];
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
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
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
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
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
1 >> A
2 A =
3 1 5 8 7 0
4 >> B
5 B =
6 1 1 0 2 3
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
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
1 >> A | B
2 ans =
3 1x5 logical array
4 1 1 0 1 1
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 >>
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 >>
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 >> 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 >>
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 >>
1 >> Y1 = discretize(data,edges)
2 Y1 =
3 NaN NaN 1 1 3 2 4 4 2 2
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 >> % bin 1 : 2 − 4
2 >> % bin 2 : 4.01 − 6
3 >> % bin 3 : 6.01 − 8
4 >> % bin 4 : 8.01 − 10
The bins now will be, based on the default option of the edges being set on the left
We might want not to specify the edges but rather specify the number of bins in which we want to
discritize our data into.
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 >> 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.
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
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.
Learning Objectives
• 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.
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.
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
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
To compute the determinant of a matrix in MatLab, we use the det function and pass the matrix as the
argument.
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
If we pass two matrices in our function, the function will compute element by element comparison.
We use the lt. It strictly checks for less than and no equality
6.5 Relational Operations 87
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
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.
Learning Objectives
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
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 returns the number of rows of a matrix and the number of columns of the same matrix as
well.
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
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.
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
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.
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.
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].
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]
1 A = [ 4 5 6 9
2 7 8 9 9
3 8 7 4 5]
Learning Objectives
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
• 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
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.
7.2.3 Integration
To compute the integration of a function f is calculated by the help of the int function.
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,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(...,’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(...,’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
Learning Objectives
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).
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.
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
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
Learning Objectives
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.
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
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
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.
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);
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
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
Learning Objectives
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
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.
Learning Objectives
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.
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 .
Learning Objectives
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
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.
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
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.
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.
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.
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
Learning Objectives
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.
If our file has different delimiter, for instance ’b’ is our delimiter in our next example.
146 Chapter 9. Importing Data into MatLab
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
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.
An example
Input
10.5 While Loops 155
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
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.
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.
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.
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
Learning Objectives
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
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)
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
1.
1 R = [A(1,1) , A(1,end) ; A(end,1), A(end,end)]
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
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;
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)))
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
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
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
6. –END–