MATLAB Course - Part 1
MATLAB Course - Part 1
MATLAB
Hans-Petter Halvorsen
https://www.halvorsen.blog
Introduction to MATLAB
MATLAB
Introduction to MATLAB
Hans-Petter Halvorsen, 2022.08.17
http://www.halvorsen.blog
Preface
Copyright You cannot distribute or copy this document without
permission from the author. You cannot copy or link to this document
directly from other sources, web pages, etc. You should always link to the
proper web page where this document is located, typically
http://www.halvorsen.blog
In this MATLAB Course, you will learn basic MATLAB and how to use
MATLAB in Control and Simulation applications. An introduction to
Simulink and other Tools will also be given.
This is a self-paced course based on this document and some short videos
on the way. This document contains lots of examples and self-paced tasks
that the users will go through and solve on their own. The user may go
through the tasks in this document in their own pace and the instructor
will be available for guidance throughout the course.
1. Introduction to MATLAB
2. Modelling, Simulation and Control
3. Simulink and Advanced Topics
In part 1 you will be familiar with the MATLAB environment and learn
basic MATLAB programming.
The course consists of lots of Tasks you should solve while reading this
course manual and watching the videos referred to in the text.
ii
Make sure to bring your headphones for the videos in this
course. The course consists of several short videos that will give you an
introduction to the different topics in the course.
Prerequisites
MATLAB Basics:
http://www.halvorsen.blog/documents/programming/matlab/matlab_basics.php
iii
MATLAB Videos:
http://www.halvorsen.blog/documents/video/matlab_basics_videos.php
On these web pages you find video solutions, complete step by step
solutions, downloadable MATLAB code, additional resources, etc.
iv
Table of Contents
Preface ............................................................................................ ii
Table of Contents.............................................................................. v
1 Introduction ............................................................................... 1
v
vi Table of Contents
7 Plotting .................................................................................... 45
9 Mathematics ............................................................................. 65
Plotting ....................................................................................... 83
http://www.halvorsen.blog/documents/programming/matlab
1
2 The MATLAB
Environment
The MATLAB Environment consists of the following main parts:
• Command Window
• Command History
• Workspace
• Current Folder
• Editor
Before you start, you should watch the video “Working in the
Development Environment”.
2
3 The MATLAB Environment
You type all your commands after the command Prompt “>>”, e.g.,
defining the following matrix:
1 2
𝐴=[ ]
0 3
>> A = [1 2;0 3]
Or
>> A = [1,2;0,3]
𝑎 + 𝑏, 𝑤ℎ𝑒𝑟𝑒 𝑎 = 4, 𝑏 = 3
>>a = 4
>>b = 3
>>a + b
ans =
7
2.3 Workspace
The Workspace window list all your variables used as long you have
MATLAB opened.
>>who
or
>>whos
This command lists all the command with the current values, dimensions,
etc.
The command clear, will clear all the variables in your workplace.
>>clear
You may also save all your variables and data to a text file (.mat file),
this is useful if you want to save your data and use it for later.
Select the variables you want to save and right-click and select “Save
As…”:
You should set your working folder as the Current Directory or set your
working folder as part of the search path, if you don’t MATLAB will not find
your files.
Search Path:
You need to use this if you want MATLAB to find your scripts and functions
you want to use.
2.5 Editor
The Editor is used to create scripts and m-files. Click the “New Script”
button in the Toolbar
When you learn about m-files (scripts and functions) in a later chapter you
will be using this editor to enter your commands and save them.
Note! In the beginning of the course (chapter 1-5) we will only use the
Command Window. In chapter 6 we will start using the Editor.
9
10 Using the Help System in MATLAB
MATLAB answers with links to lots of Help topics. You may also type more
specific, e.g., “Help elfun” (Elementary Math Functions), and MATLAB will
list all functions according to the specific category.
If you type “help <functionname>” you will get specific help about this
function.
You may also type “doc <topic>” to open the Help window on the
specific topic of interest.
Searching:
We can use the help keyword when we want to get help for a specific
function, but if we want to search for all functions, etc. with a specific
keyword you may use the lookfor command.
Example:
lookfor plot
[End of Example]
Example:
>> x = 17
x =
17
>> x = 'hat'
x =
hat
>> x = [3*4, pi/2]
x =
12.0000 1.5708
>> y = 3*sin(x)
y =
-1.6097 3.0000
[End of Example]
Note! MATLAB is case sensitive! The variables 𝑥 and 𝑋 are not the same.
11
12 MATLAB Basics
>> a=5
a =
5
>> a=6;
>>
As you see, when you type a semicolon (;) after the command, MATLAB
will not respond. This is very useful because sometimes you want MATLAB
to respond, while in other situations that is not necessary.
Built-in constants:
Name Description
i, j Used for complex numbers, e.g., z=2+4i
pi 𝜋
inf ∞, Infinity
NaN Not A Number. If you, e.g., divide by zero, you get NaN
To avoid choosing a name for a new variable that might conflict with a
name already in use, check for any occurrences of the name using the
which command:
Example:
>> which -all pi
built-in (C:\Matlab\R2007a\toolbox\matlab\elmat\pi)
You may also use the iskeyword command. This command causes
MATLAB to list all reserved names.
>> iskeyword
ans =
'break'
'case'
'catch'
'classdef'
'continue'
'else'
'elseif'
'end'
'for'
'function'
'global'
'if'
'otherwise'
'persistent'
'return'
'switch'
'try'
'while'
Note! You cannot assign these reserved names as your variable names.
Example:
>> sin=4
sin =
4
>> sin(3)
??? Index exceeds matrix dimensions.
In this example you have defined a variable “sin” – but “sin” is also a
built-in function – and this function will no longer work!
If you accidently do so, use the clear command to reset it back to normal.
[End of Example]
>>y=16;
>>z=3;
>>y+z
Note! When you use a semicolon, no output will be displayed. Try the
code above with and without semicolon.
Note! Some functions display output even if you use semicolon, like plot,
etc.
>>16-3
>>16/3
>>16*3
→ Try them.
[End of Task]
Built-in Functions:
Here are some descriptions for the most used basic built-in MATLAB
functions.
<function>
who, whos who lists in alphabetical order all variables in >>who
>>whos
the currently active workspace.
clear Clear variables and functions from memory. >>clear
>>clear x
Before you start, you should use the Help system in MATLAB to read more
about these functions. Type “help <functionname>” in the Command
window.
Create a random vector with 100 random numbers between 0 and 100.
Find the minimum value, the maximum value, the mean and the standard
deviation using some of the built-in functions in MATLAB listed above.
[End of Task]
Matrices and vectors (Linear Algebra) are the basic elements in MATLAB
and also the basic elements in control design theory. So, it is important
you know how to handle vectors and matrices in MATLAB.
1 2
𝐴=[ ]
3 4
>> A = [1 2; 3 4]
A = 1 2
3 4
or:
>> A = [1, 2; 3, 4]
A = 1 2
3 4
>> A(2,1)
ans =
3
or:
>> A(:,1)
ans =
1
3
or:
>> A(2,:)
ans =
3 4
Example:
This example shows how to use the colon notation creating a vector and
do some calculations.
[End of Example]
1
𝑥 = [2]
3
0 1
𝐴=[ ]
−2 −3
−1 2 0
𝐶=[ 4 10 −2]
1 0 6
→ Use Use MATLAB to find the value in the second row and the third
column of matrix 𝐶.
[End of Task]
You can delete rows and columns from a matrix using just a pair of square
brackets [].
Example:
Given:
0 1
𝐴=[ ]
−2 −3
>>A=[0 1; -2 -3];
>>A(:,2) = []
A =
0
-2
[End of Example]
When creating variables and constants, make sure you create a name that
is not already exists in MATLAB. Note also that MATLAB is case sensitive!
The variables x and X are not the same.
Use the which command to check if the name already exists: which –all
<your name>
Example:
>> which -all sin
built-in (C:\Matlab\R2007a\toolbox\matlab\elfun\@double\sin) %
double method
built-in (C:\Matlab\R2007a\toolbox\matlab\elfun\@single\sin) %
single method
If you need to write large or small numbers, like 2 𝑥 105 , 7.5 𝑥 10−8you can
use the “e” notation, e.g.:
>> 2e5
ans =
200000
>> 7.5e-8
ans =
7.5000e-008
Line Continuation:
For large arrays, it may be difficult to fit one row on one command line.
We may then split the row across several command lines by using the line
continuation operator “...”.
Example:
>> x=[1 2 3 4 5 ...
6 7 8 9 10]
x =
1 2 3 4 5 6 7 8 9 10
Example:
>> x=1,y=2,z=3
x =
1
y =
2
z =
3
Given
𝑎11 𝑎12 𝑏11 𝑏12
𝐴 = [𝑎 𝑎22 ] , 𝐵 = [ ]
21 𝑏21 𝑏22
Then
𝑎 𝑏 𝑎12 𝑏12
𝐴.∗ 𝐵 = [ 11 11 ]
𝑎21 𝑏21 𝑎22 𝑏22
Example:
>> A = [1; 2; 3]
A =
1
2
3
>> B = [-6; 7; 10]
B =
-6
7
10
>> A*B
??? Error using ==> mtimes
Inner matrix dimensions must agree.
>> A.*B
ans =
-6
14
30
[End of Example]
MATLAB are well suited for Linear Algebra. This chapter assumes you have
some basic understanding of Linear Algebra and matrices and vectors.
You may also type “help <functionname>” for help about a specific
function.
Before you start, you should use the Help system in MATLAB to read more
about these functions. Type “help <functionname>” in the Command
window.
5.1 Vectors
Given a vector 𝑥:
23
24 Linear Algebra; Vectors and Matrices
𝑥1
𝑥2
𝑥 = [ ⋮ ] ∈ 𝑅𝑛
𝑥𝑛
Example:
Given:
1
𝑥 = [2]
3
>> x=[1; 2; 3]
x =
1
2
3
𝑥 𝑇 = [𝑥1 𝑥2 ⋯ 𝑥𝑛 ] ∈ 𝑅1𝑥𝑛
>> x'
ans =
1 2 3
[End of Example]
Example:
The length of a vector most makes sense for 2 or 3 dimensional vectors.
𝑣 = [3, 4]
|𝑣 | = √32 + 42 = √9 + 16 = √25 = 5
MATLAB:
>> v = [3,4]'
>> l = sqrt(3^2 + 4^2)
l =
5
Or using the general formula shown above (which works for any
dimensions):
>> l = sqrt(v'*v)
l =
5
Note!
>> length(v)
ans =
2
The built-in function length() don’t give the actual length of the vector but
finds number of elements in the vector or array, i.e., the size of the array.
[End of Example]
Orthogonality:
𝑥𝑇𝑦 = 0
5.2 Matrices
Given a matrix 𝐴:
𝑎11 ⋯ 𝑎1𝑚
𝐴=[ ⋮ ⋱ ⋮ ] ∈ 𝑅𝑛𝑥𝑚
𝑎𝑛1 ⋯ 𝑎𝑛𝑚
Example:
0 1
𝐴=[ ]
−2 −3
[End of Example]
5.2.1 Transpose
The Transpose of matrix 𝐴:
𝑎11 ⋯ 𝑎𝑛1
𝐴𝑇 =[ ⋮ ⋱ ⋮ ] ∈ 𝑅𝑚𝑥𝑛
𝑎1𝑚 ⋯ 𝑎𝑛𝑚
Example:
0 1 𝑇 0 −2
𝐴𝑇 = [ ] =[ ]
−2 −3 1 −3
>> A'
ans =
0 -2
1 -3
[End of Example]
5.2.2 Diagonal
The Diagonal elements of matrix A is the vector
Example:
>> diag(A)
ans =
0
-3
[End of Example]
𝜆1 0 ⋯ 0
0 𝜆2 ⋯ 0
Λ=[ ] ∈ 𝑅𝑛𝑥𝑛
⋮ ⋮ ⋱ ⋮
0 0 ⋯ 𝜆𝑛
1 0 ⋯ 0
0 1 ⋯ 0
𝐼=[ ] ∈ 𝑅𝑛𝑥𝑚
⋮ ⋮ ⋱ ⋮
0 0 ⋯ 1
Example:
>> eye(3)
ans =
1 0 0
0 1 0
0 0 1
[End of Example]
5.2.3 Triangular
Lower Triangular matrix L:
. 0 0
𝐿 = [⋮ ⋱ 0]
. ⋯ .
𝐶 = 𝐴𝐵 ∈ 𝑅𝑛𝑥𝑝
where
𝑛
Example:
>> A = [0 1; -2 -3]
A =
0 1
-2 -3
>> B = [1 0;3 -2]
B =
1 0
3 -2
>> A*B
ans =
3 -2
-11 6
[End of Example]
Note!
Note!
𝐴𝐵 ≠ 𝐵𝐴
𝐴(𝐵𝐶 ) = (𝐴𝐵 )𝐶
(𝐴 + 𝐵 )𝐶 = 𝐴𝐶 + 𝐵𝐶
𝐶 (𝐴 + 𝐵 ) = 𝐶𝐴 + 𝐶𝐵
𝐶 = 𝐴 + 𝐵 ∈ 𝑅 𝑛𝑥𝑚
Example:
>> A = [0 1; -2 -3]
>> B = [1 0; 3 -2]
>> A + B
ans =
1 1
1 -5
[End of Example]
5.2.6 Determinant
Given a matrix 𝐴 ∈ 𝑅𝑛𝑥𝑛, then the Determinant is given by:
𝑑𝑒𝑡(𝐴) = |𝐴 |
Then
Example:
A =
0 1
-2 -3
>> det(A)
ans =
2
[End of Example]
Notice that
and
Example:
>> det(A*B)
ans =
-4
>> det(A)*det(B)
ans =
-4
>> det(A')
ans =
2
>> det(A)
ans =
2
[End of Example]
𝐴−1
if
𝐴𝐴−1 = 𝐴−1 𝐴 = 𝐼
1 𝑎22 −𝑎12
𝐴−1 = [−𝑎 𝑎11 ] ∈ 𝑅
2𝑥2
𝑑𝑒𝑡 (𝐴) 21
Example:
A =
0 1
-2 -3
>> inv(A)
ans =
-1.5000 -0.5000
1.0000 0
Notice that:
𝐴𝐴−1 = 𝐴−1 𝐴 = 𝐼
[End of Example]
5.3 Eigenvalues
Given 𝐴 ∈ 𝑅𝑛𝑥𝑛, then the Eigenvalues is defined as:
𝑑𝑒𝑡 (𝜆𝐼 − 𝐴) = 0
Example:
A =
0 1
-2 -3
>> eig(A)
ans =
-1
-2
[End of Example]
In this task we will practice on entering matrices and perform basic matrix
operations.
0 1 1 0 1 −1
𝐴=[ ], 𝐵=[ ], 𝐶=[ ]
−2 −3 3 −2 −2 2
• 𝐴+𝐵
• 𝐴−𝐵
• 𝐴𝑇
• 𝐴−1
• 𝑑𝑖𝑎𝑔 (𝐴) , 𝑑𝑖𝑎𝑔(𝐵)
• 𝑑𝑒𝑡 (𝐴), 𝑑𝑒𝑡(𝐵)
• 𝑑𝑒𝑡 (𝐴𝐵 )
• 𝑒𝑖𝑔 (𝐴)
• 𝐴𝐵 ≠ 𝐵𝐴
• 𝐴(𝐵𝐶 ) = (𝐴𝐵 )𝐶
• (𝐴 + 𝐵 )𝐶 = 𝐴𝐶 + 𝐵𝐶
• 𝐶 (𝐴 + 𝐵 ) = 𝐶𝐴 + 𝐶𝐵
• det(𝐴𝐵 ) = det(𝐴) det(𝐵 )
• det(𝐴𝑇 ) = det (𝐴)
• 𝐴𝐴−1 = 𝐴−1 𝐴 = 𝐼
By “proving”, I mean enter the left side in MATLAB, then enter the right
side, then check if you get the same results or not. In that way you have
“proved” it.
[End of Task]
In MATLAB we can also simply use the backslash operator “\” in order to
find the solution like this:
x = A\b
Example:
Given the following equations:
𝑥1 + 2𝑥2 = 5
3𝑥1 + 4𝑥2 = 6
7𝑥1 + 8𝑥2 = 9
𝐴𝑥 = 𝑏
1 2
𝐴 = [3 4]
7 8
5
𝑏 = [6]
9
Normally we can find the solution by taking the inverse of the A matrix:
𝑥 = 𝐴−1 𝑏
>> A = [1 2; 3 4; 7 8];
>> b = [5;6;9];
>> x = inv(A)*b
Error using inv
Matrix must be square.
A = [1 2; 3 4; 7 8];
b = [5;6;9];
x = A\b
x=
-3.5000
4.1786
Actually, when using the backslash operator “\” in MATLAB it uses the LU
factorization as part of the algorithm to find the solution.
We could have used the known Least Square Method formula as well.
Given:
𝐴𝑥 = 𝑏
Then the Least Square Method formula is given by (how we can derive
this equation will not be shown here):
Let’s try:
A = [1 2; 3 4; 7 8];
b = [5;6;9];
x_ls = inv(A'*A)*A'*b
x=
-3.5000
4.1786
This means using the Least Square formula also works fine in this case. It
gives same results as using the backslash. "\" operator in this case. In
general, the backslash operator is better to use because it finds the best
way to solve the equations. MATLAB does the "dirty work" for you.
𝑥1 + 2𝑥2 = 5
3𝑥1 + 4𝑥2 = 6
𝐴𝑥 = 𝑏
Solve the equations, i.e., find 𝑥1, 𝑥2, using MATLAB. It can be solved like
this:
𝐴𝑥 = 𝑏 → 𝑥 = 𝐴−1 𝑏
[End of Task]
Before you start, you should watch the video “Writing a MATLAB
Program”.
Below we see the MATLAB Editor that we use to create Scripts and
Functions (both are saved as .m files):
Scripts:
Functions:
MATLAB have lots of built-in functions, but very often we need to create
our own functions (these are called user-defined functions)
6.2 Scripts
A Script is a collection of MATLAB commands and functions that is bundled
together in a m-file. When you run the Script, all the commands are
executed sequentially.
The built-in Editor for creating and modifying m-files are shown below:
In the Editor you create a sequence of MATLAB commands that you save
as a m-file (the file extension ends with .m). Push the “Run” button when
you want to run your program.
If the code contains errors or warning the MATLAB compiler will let you
know by displaying some colors symbols to the right in the Editor, as
shown on the Figure above.
Running a m-file in the Command window (just type the name of the m-
file and hit Enter to run the m-file):
You may open or edit a m-file using the open button in the toolbar.
Task 6: Script
Create a Script (M-file) where you create a vector with random data and
find the average and the standard deviation
[End of Task]
6.3 Functions
MATLAB includes more than 1000 built-in functions that you can use, but
sometimes you need to create your own functions.
Or in more detail:
The first line of a function M-file starts with the keyword function. It gives
the function name and order of arguments. In example above, we have 3
input arguments (i.e, 𝑎, 𝑏, 𝑐) and 2 output arguments (i.e, 𝑥, 𝑦).
The first line of the help text is the H1 line, which MATLAB displays when
you use the lookfor command or the help command.
A Function can have one or more inputs and one or more outputs.
Below we see how to declare a function with one input and one output:
Below we see how to declare a function with multiple inputs and multiple
outputs:
Example:
Here is a simple Example:
Note! The function name (add) and the name of the file (“add.m”) need
to be identical.
% Example 1:
add(2,3)
% Example 2:
a = 4;
b = 6;
add(a,b);
% Example 3:
answer = add(a,b)
[End of Example]
You may create your own functions and save them as a m-file. Functions
are M-files that can accept input arguments and return output arguments.
Functions operate on variables within their own workspace, separate from
the workspace you access at the MATLAB command prompt.
Note! The name of the M-file and of the function should be the same!
Example:
Below we see how the m-file for this function looks like:
You may define 𝐴 and 𝑏 in the Command window and the use the
function on order to find 𝑥:
From the Command window you can then type “help <function name>”
in order to read this information:
[End of Example]
To avoid choosing a name for a new function that might conflict with a
name already in use, check for any occurrences of the name using this
command:
>>x = 2;
>>y = 4;
>>z = calc_average(x,y)
[End of Task]
Create a function circle that finds the area in a circle based on the input
parameter 𝑟 (radius).
[End of Task]
Plots functions: Here are some useful functions for creating plots:
title('string')
xlabel Add xlabel to current plot >> xlabel('time')
xlabel('string')
ylabel Add ylabel to current plot >> ylabel('temperature')
ylabel('string')
legend Creates a legend in the corner (or at a specified >> legend('temperature')
Before you start, you should use the Help system in MATLAB to read more
about these functions. Type “help <functionname>” in the Command
window.
Example:
Here we see some examples of how to use the different plot functions:
45
46 Plotting
[End of Example]
Before you start using these functions, you should watch the video
“Using Basic Plotting Functions”.
Task 9: Plotting
In the Command window (or use the Script Editor) in MATLAB window
input the time from 𝑡 = 0 seconds to 𝑡 = 10 seconds in increments of 0.1
seconds as follows:
>>t = [0:0.1:10];
>>y = cos(t);
>>plot(t,y)
[End of Task]
Example:
x = 0:pi/100:2*pi;
y = sin(x);
y2 = sin(x-.25);
y3 = sin(x-.5);
plot(x,y, x,y2, x,y3)
x=0:0.01:2*pi;
plot(x, sin(x))
hold on
plot(x, cos(x))
hold off
[End of Example]
You can also do the plotting in different plots using the figure()
command.
Example:
x=0:0.01:2*pi;
figure(1)
plot(x, sin(x))
figure(2)
plot(x, cos(x))
[End of Example]
𝑥̇ = 𝑎𝑥
1
where 𝑎 = − ,where 𝑇 is the time constant
𝑇
𝑥 (𝑡) = 𝑒 𝑎𝑡 𝑥0
→ Create a Script in MATLAB (.m file) where you plot the solution 𝑥(𝑡) in
the time interval 0 ≤ 𝑡 ≤ 25
→ Add Grid, and proper Title and Axis Labels to the plot.
[End of Task]
subplot(m,n,p)
Example:
t = 0:pi/10:2*pi;
[X,Y,Z] = cylinder(4*cos(t));
subplot(2,2,1); mesh(X)
subplot(2,2,2); mesh(Y)
subplot(2,2,3); mesh(Z)
subplot(2,2,4); mesh(X,Y,Z)
This gives:
[End of Example]
[End of Task]
7.3 Custimizing
There is lots of customizing you can do with plots, e.g., you can add a
title, x- and y-axis labels, add a legend and customize line colors and line-
styles.
The functions for doing this is; title, xlabel, ylabel, legend, etc.
Example:
x=0:0.1:2*pi;
plot(x, sin(x))
%Customize the Plot:
title('This is a Title')
xlabel('This is a X label')
ylabel('This is a y label')
legend('sin(x)')
grid on
[End of Example]
For line colors and line-styles we have the following properties we can use
for the plot function:
Line Styles:
Marker specifiers:
Colors:
Example:
>> x=0:0.1:2*pi;
>> plot(x, sin(x), 'r:o')
[End of Example]
Check out the help for the following 2D functions in MATLAB: loglog,
semilogx, semilogy, plotyy, polar, fplot, fill, area, bar, barh, hist, pie,
errorbar, scatter.
[End of Task]
• For loop
• While loop
If you want to control the flow in your program, you may want to use one
of the following:
• If-else statement
• Switch and case statement
It is assumed you know about For Loops, While Loops, If-Else and Switch
statements from other programming languages, so we will briefly show
the syntax used in MATLAB and go through some simple examples.
if expression1
statements1
elseif expression2
statements2
else
statements3
end
57
58 Flow Control and Loops
Example:
Here are some simple code snippets using the if sentence:
n=5
if n > 2
M = eye(n)
elseif n < 2
M = zeros(n)
else
M = ones(n)
end
or:
n=5
if n == 5
M = eye(n)
else
M = ones(n)
end
[End of Example]
Example:
if A == B, ...
Note! If A and B are scalars this works – but If A and B are matrices this
might not work as expected!
→ Try it!
Use instead:
→ Try it!
[End of Example]
Operators:
Logical Operators:
𝑎𝑥 2 + 𝑏𝑥 + 𝑐 = 0
−𝑏 ± √𝑏 2 − 4𝑎𝑐
, 𝑎≠0
2𝑎
𝑐
𝑥= − , 𝑎 = 0, 𝑏 ≠ 0
𝑏
∅, 𝑎 = 0, 𝑏 = 0, 𝑐 ≠ 0
{ ℂ, 𝑎 = 0, 𝑏 = 0, 𝑐 = 0
→ Create a function that finds the solution for x based on different input
values for a, b and c, e.g.,
function x = solveeq(a,b,c)
…
→ Test the function from the Command window to make sure it works as
expected, e.g.,
Tip! For ∅, you can just type disp(‘there is no solution’) and for ℂ you can
type disp(‘any complex number is a solution’) – or something like that.
[End of Task]
switch variable
case case_value1
statements1
case case_value2
statements2
…
otherwise
statements
end
Example:
n=2
switch(n)
case 1
M = eye(n)
case 2
M = zeros(n)
case 3
M = ones(n)
end
[End of Example]
Create a function that finds either the Area or the circumference of a circle
using a Switch-Case statement
>> r=2;
>> calccircl(r,1) % 1 means area
>> calccircl(r,2) % 2 means circumference
[End of Task]
Example:
m=5
for n = 1:m
r(n) = rank(magic(n));
end
r
[End of Example]
By definition, the first two Fibonacci numbers are 0 and 1, and each
subsequent number is the sum of the previous two. Some sources omit
the initial 0, instead beginning the sequence with two 1s.
𝑓𝑛 = 𝑓𝑛−1 + 𝑓𝑛−2
𝑓0 = 0, 𝑓1 = 1
>> N=10;
>> fibonacci(N)
ans =
0
1
1
2
3
5
8
13
21
34
[End of Task]
while expression
statements
end
Example:
m=5;
while m > 1
m = m - 1;
zeros(m)
end
[End of Example]
>> maxnumber=2000;
>> fibonacci(maxnumber)
[End of Task]
[End of Task]
Create a function where you use the “if-else” statement to find elements
larger than a specific value in the task above. If this is the case, discard
these values from the calculated average.
x =
4 6 12
>> calc_average(x)
ans =
5
[End of Task]
𝑧 = 3𝑥 2 + √𝑥 2 + 𝑦 2 + 𝑒 ln (𝑥)
[End of Task]
9.2 Statistics
Some Statistics functions in MATLAB: mean, max, min, std, etc.
Create a vector with random numbers between 0 and 100. Find the
following statistics: mean, median, standard deviation, minimum,
maximum and the variance.
[End of Task]
65
66 Mathematics
Example:
>> sin(pi/4)
ans =
0.7071
[End of Example]
This gives:
180
𝑑 [𝑑𝑒𝑔𝑟𝑒𝑒𝑠] = 𝑟[𝑟𝑎𝑑𝑖𝑎𝑛𝑠] ∙ ( )
𝜋
𝜋
𝑟[𝑟𝑎𝑑𝑖𝑎𝑛𝑠] = 𝑑[𝑑𝑒𝑔𝑟𝑒𝑒𝑠] ∙ ( )
180
[End of Task]
→ Create a function that finds the angle 𝐴 (in degrees) based on input
arguments (𝑎, 𝑐), (𝑏, 𝑐) and (𝑎, 𝑏) respectively.
Use, e.g., a third input “type” to define the different types above.
→ Use you previous function r2d() to make sure the output of your
function is in degrees and not in radians.
𝑐 2 = 𝑎2 + 𝑏 2
Testing the function can be done like this in the Command Window:
32.0054
We also see that the answer in this case is the same, which is expected.
[End of Task]
Given:
𝑐 2 = 𝑎2 + 𝑏 2 − 2𝑎𝑏 𝑐𝑜𝑠𝐶
[End of Task]
Make sure to add labels and a legend and use different line styles and
colors for the plots.
[End of Task]
𝑧 = 𝑎 + 𝑖𝑏
or
𝑧 = 𝑎 + 𝑗𝑏
𝑖 = √−1
Where 𝑎 is called the real part of 𝑧 and 𝑏 is called the imaginary part of
𝑧, i.e.:
𝑅𝑒(𝑧) = 𝑎, 𝐼𝑚(𝑧) = 𝑏
𝑧 = 𝑟𝑒 𝑗𝜃
where:
𝑟 = |𝑧 | = √ 𝑎2 + 𝑏 2
𝑏
𝜃 = 𝑎𝑡𝑎𝑛
𝑎
Example:
Given the following complex number:
𝑧 = 2 + 𝑖3
>> z=2+3i
or:
>> z=2+3j
[End of Example]
𝑧 ∗ = 𝑎 − 𝑖𝑏
Multiplication:
𝑧3 = 𝑧1 𝑧2 = 𝑟1 𝑟2 𝑒 𝑗(𝜃1+𝜃2 )
Division:
𝑧1 𝑟1 𝑒 𝑗𝜃1 𝑟1 𝑗(𝜃 −𝜃 )
𝑧3 = = = 𝑒 1 2
𝑧2 𝑟2 𝑒 𝑗𝜃2 𝑟2
MATLAB functions:
𝑐 = 4 + 𝑗3, 𝑑 = 1 − 𝑗
Use the direct method supported by MATLAB and the specific complex
functions abs, angle, imag, real, conj, complex, etc. together with the
formulas for complex numbers that are listed above in the text (as you do
it when you should calculate it using pen & paper).
[End of Task]
𝑥 2 + 4𝑥 + 13
[End of Task]
9.5 Polynomials
A polynomial is expressed as:
Example:
Given the polynomial:
In MATLAB we write:
[End of Example]
𝑝(𝑥 ) = −2.1𝑥 4 + 2𝑥 3 + 5𝑥 + 11
→ Find the roots of the polynomial (𝑝(𝑥 ) = 0) (and check if the answers are
correct)
→ Find 𝑝(𝑥 = 2)
[End of Task]
𝑝1 (𝑥 ) = 1 + 𝑥 − 𝑥 2
𝑝2 (𝑥 ) = 2 + 𝑥 3
→ Find the polynomial 𝑝(𝑥) = 𝑝1 (𝑥) ∙ 𝑝2 (𝑥) using MATLAB and find the roots
→ Find 𝑝(𝑥 = 2)
[End of Task]
Find the 6. order Polynomial that best fits the following function:
𝑦 = sin (𝑥)
→ Plot both the function and the 6. order Polynomial to compare the
results.
[End of Task]
function h = pyt(a,b)
% ..
…
h = …
[End of Task]
𝐸 = 𝑚𝑐 2
→ Calculate how much of the mass on the sun is used to create this
energy per day.
75
76 Additional Tasks
→ How many years will it take to convert all the mass of the sun
completely? Do we need to worry if the sun will be used up in our
generation or the next?
[End of Task]
Create a function that finds the surface area of a cylinder based on the
height (ℎ) and the radius (𝑟) of the cylinder.
[End of Task]
Given 𝑎 = 1, 𝑏 = 3, 𝑐 = 5
→ Find 𝑓(9)
Tip! You should split the expressions into different parts, such as:
poly = 𝑎𝑥 2 + 𝑏𝑥 + 𝑐
num =…
den =….
f =…
This makes the expression simpler to read and understand, and you
minimize the risk of making an error while typing the expression in
MATLAB.
[End of Task]
𝑥1 + 2𝑥2 = 5
3𝑥1 + 4𝑥2 = 6
7𝑥1 + 8𝑥2 = 9
[End of Task]
We will use the functions tic and toc to find the execution time.
end
toc
y=zeros(tmax,1); % preallocating
for t=1:tmax
y(t,1)=cos(t);
end
toc
We will improve the Script further by removing the For Loop by using
vectorization instead:
% Test 3: Vectorization
clear
tic
tmax = 100000;
t = 1:tmax; %vectorization
y = cos(t);
toc
[End of Task]
𝐶 = 𝐴𝐵 ∈ 𝑅𝑛𝑥𝑝
where
𝑛
But her you will create your own function that multiply two matrices:
function C = matrixmult(A,B)
…
[End of Task]
The first 25 prime numbers (all the prime numbers less than 100) are:
2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71,
73, 79, 83, 89, 97
Create a MATLAB Script where you find all prime numbers between 1 and
200.
Tip! I guess this can be done in many ways, but one way is to use 2
nested For Loops.
[End of Task]
The first 25 prime numbers (all the prime numbers less than 100) are:
2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71,
73, 79, 83, 89, 97
You can check the function in the Command Window like this:
>> number = 4
>> checkifprime(number)
[End of Task]
Built-in Constants
MATLAB have several built-in constants. Some of them are explained
here:
Name Description
i, j Used for complex numbers, e.g., z=2+4i
pi 𝜋
inf ∞, Infinity
NaN Not A Number. If you, e.g., divide by zero, you get NaN
Basic Functions
Here are some descriptions for the most used basic MATLAB functions.
<function>
who, whos who lists in alphabetical order all variables in >>who
>>whos
the currently active workspace.
clear Clear variables and functions from memory. >>clear
>>clear x
82
83 Appendix A: MATLAB Functions
Linear Algebra
Here are some useful functions for Linear Algebra in MATLAB:
You may also type “help <functionname>” for help about a specific
function.
Plotting
Plots functions: Here are some useful functions for creating plots:
axis Control axis scaling and appearance. “axis([xmin >>axis([xmin xmax ymin ymax])
>>axis off
xmax ymin ymax])” sets the limits for the x- and >>axis on
y-axis of the current axes.
title Add title to current plot >>title('this is a title')
title('string')
xlabel Add xlabel to current plot >> xlabel('time')
xlabel('string')
ylabel Add ylabel to current plot >> ylabel('temperature')
ylabel('string')
legend Creates a legend in the corner (or at a specified >> legend('temperature')
Operators:
Logical Operators
You may use the following logical operators in MATLAB:
Complex Numbers
Functions used to create or manipulate complex numbers.
E-mail: hans.p.halvorsen@usn.no
Blog: http://www.halvorsen.blog