Introduction To MATLAB - Overview
Introduction To MATLAB - Overview
Introduction to MATLAB
Hans-Petter Halvorsen
https://www.halvorsen.blog
What is MATLAB?
• MATLAB is a tool for technical computing, computation and
visualization in an integrated environment.
• MATLAB is an abbreviation for MATrix LABoratory
• It is well suited for Matrix manipulation and problem solving
related to Linear Algebra, Modelling, Simulation and Control
Applications
• Popular in Universities, Teaching and Research
MATLAB Syntax - Example
clear
clc
close all
x=[0, 1, 2, 3, 4 ,5];
Defining Vectors y=[15, 10, 9, 6, 2 ,0];
p = polyfit(x,y,n)
ymodel = polyval(p,x);
subplot(3,2,n)
Built-in Functions plot(x,y,'o',x,ymodel)
title(sprintf('Model order %d', n));
end
Lessons
1. The MATLAB Environment (IDE)
2. MATLAB Basics
3. Vectors and Matrices
4. Plotting
5. Scripts (m-files)
6. User-defined Functions
7. Flow Control (if...elseif...else, while, switch...case)
Lesson 1
http://www.mathworks.com/videos/working-in-the-development-environment-69021.html
The MATLAB Environment (IDE)
Script Editor
Current Workspace
Folder
Plot Window
Command Window
MATLAB Basics
http://www.mathworks.com/videos/getting-started-with-matlab-68985.html
MATLAB Basics
Command Window
The Command Window is the main window in MATLAB. Use the Command Window to
enter variables and to run functions and M-files scripts (more about m-files later). Its like
an advanced calculator!
Unlike many other languages, where the semicolon is used to terminate commands, in
MATLAB the semicolon serves to suppress the output of the line that it concludes.
MATLAB Basics
Solutions:
>> x=2;, y=2
>> z = 3*x^2 + sqrt(x^2 + y^2) + exp(log(x))
ans =
16.8284
...
MATLAB Basics
Students: Use MATLAB in order to find the surface area (𝐴) of a
cylinder based on the height (ℎ) and the radius (𝑟) of the cylinder
𝑟=3
ℎ=8 𝐴 =?
MATLAB Basics
Students: Find the surface area of a cylinder based on
the height (ℎ) and the radius (𝑟) of the cylinder
Solutions:
>> h=8
>> r=3
>> A = 2*pi*r^2 +2*pi*r*h;
A =
207.3451
Whats next?
Learning by Doing!
http://www.mathworks.com/videos/working-with-arrays-in-matlab-69022.html
Vectors & Matrices
• Matrices and vectors (Linear Algebra) are the basic elements in MATLAB
and also the basic elements in control design theory, etc.
• All variables in MATLAB is a matrix (but with different dimensions)
• So it is important you know how to handle vectors and matrices in
MATLAB and in general
Vectors
Examples of different Rows and Columns vectors
>> x*y
>> x = [1, 2, 3] >> y*x
Students: Define these vectors in
MATLAB. Try also to multiply the >> x*z
>> y = [4; 5; 6] different vectors like this: >> y*z
...
>> z = [8, 9, 10]'
>> b = [1:2:10]
>> b = [1:0.5:4]
Vectors
Given the following Rain Data for a given Week (Monday to Sunday):
Day Rain We define the Data in MATLAB like this:
Amount
Monday 2,1 mm
>> x = [2.1, 10, 9.7, 6.2, 2.5, 0, 8.5]
Tuesday 10 mm
Wednesday 9,7 mm
If we are only interested in the Rain Amount on Monday:
Thursday 6,2 mm >> x(1)
Friday 2,5 mm ans = 2.1000
Saturday 0 mm
Sunday 8,3 mm Rain Amount on Friday:
>> x(5)
ans = 2.5000
2
-10
-9
171
136
4 -7 78
y = Multiplication 5 -6 55
8
-4
-3
21
10
0 1 6 15 28 What is 𝑦 3 =? 9
10
-2
-1
3
12 1 6
190 231 ans = 28 13 2 15
14 3 28
15 4 45
We can also do like this: 16 5 66
>> x = 3; 17 6 91
examples y = 28
20 9 190
21 10 231
Matrices
Students: Define the following
matrices in MATLAB
>> A = [1 2; 3 4]
A = 1 2
3 4
>> rank(A)
>> det(A)
>> inv(A)
>> inv(B)
>> eig(A)
>> A*B >> A*(B*C) >> inv(A)
>> B*A >> (A*B)*C >> inv(B)
>> A+B >> (A+B)*C >> diag(A)
>> B' >> A*C + C*B >> inv(A)*A
>> B'*C >> (A+inv(B))*C >> A*inv(A)
>> A*B'
>> A'*B’ ... ...
>> A.*B
...
Plotting
http://www.mathworks.com/videos/using-basic-plotting-functions-69018.html
Plotting
>> x = 0:0.1:2*pi;
>> y = sin(x);
>> plot(x,y)
...
>> plot(x,y,'r*', x,y2,'g+')
Plotting
Plotting functions:
Students: Try this example
Name Description
plot Create a Plot >> x=0:0.1:2*pi;
>> y=sin(x);
figure Define a new Figure/Plot window
>> plot(x,y)
grid on/off Create Grid lines in a plot >> title('Plot Example')
title Add Title to current plot >> xlabel('x')
>> ylabel('y=sin(x)')
xlabel Add a Label on the x-axis
>> grid on
ylabel Add a Label on the x-axis >> axis([0,2*pi,-1,1])
axis Set xmin,xmax,ymin,ymax >> legend(’Temperature')
hold on/off Add several plots in the same Figure
legend Create a legend in the corner (or at a
specified position) of the plot Students: Try also to change
subplot Divide a Figure into several Subplots some of the commands and see
what happens with the plot
Plotting
Given the following Rain Data for a given Week (Monday to Sunday):
Day Rain Amount
Monday 2,1 mm
Tuesday 10 mm
Wednesday 9,7 mm
Thursday 6,2 mm
Students: Plot these Values
Friday 2,5 mm
Saturday 0 mm
Sunday 8,3 mm
Solution Plotting
Day Rain x = [2.1, 10, 9.7, 6.2, 2.5, 0, 8.5]
Amount >> plot(x, 'o')
Monday 2,1 mm
Tuesday 10 mm
Wednesday 9,7 mm
Thursday 6,2 mm
Friday 2,5 mm
Saturday 0 mm
Sunday 8,3 mm
Plotting
𝑦 𝑥 = 2𝑥 2 + 3𝑥 + 1
• Scripts (m-files)
• User-defined Functions
Scripts (m-files)
http://www.mathworks.com/videos/writing-a-matlab-program-69023.html
Scripts (m-files) MATLAB Scripts are saved as so-called .m files (file extension is .m)
When using the Script Editor, you may create several lines of code and execute
Script Editor all in one batch. You can easily do changes in your code, create comments, etc.
clear
clc
x=0:0.1:2*pi;
y=sin(x);
y2=cos(x);
y3=tan(x);
y4=atan(x);
%plotting sin(x)
subplot(2,2,1)
plot(x,y)
%plotting cos(x)
Run the Script subplot(2,2,2)
plot(x,y2)
%plotting tan(x)
subplot(2,2,3)
plot(x,y3)
%plotting atan(x)
Students: Try this example subplot(2,2,4)
plot(x,y4)
User-defined Functions
MATLAB contains hundreds of built-in functions, but very often you need to create your own functions
Input
>> Tc = 20;
>> Tf =
fahrenheit(Tc)
Tf =
t = 0:0.1:24;
Tc = (sin(t)+1)*20;
Tf = fahrenheit(Tc);
function Tf = fahrenheit(Tc)
% This function converts a temperature from celsius to plot(t,Tc, t,Tf)
fahrenheit
title('Temperature Simulation')
Tf = (9/5)*Tc + 32; xlabel('t')
ylabel('Temperature')
grid on
axis([0,24, 0,120]);
legend('Celcius', 'Fahrenheit')
Whats next?
Learning by Doing!
The behavior is the same as in other programming languages. 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.
Flow Control
if –elseif-else
Run the Script several times with different
Students: Try this example values of n and see what happens
clear Note!!!
clc
clear
clc
n=1;
“if-elseif-else” and “switch-case-
switch(n)
case 1 otherwise” is very similar in use
disp('n=1')
case 2
disp('n=2')
case 3
disp('n=3')
otherwise
disp('n is not 1, 2 or 3')
end
Flow Control
for loop
Students: Create a script that sums all
Students: Try this example the numbers in a vector (array)
clear
clc
Solution:
x = [4, 6, 3, 9, 22, 11]; clear
clc
N = length(x);
x = [4, 6, 3, 9, 22, 11];
for i=1:N
x(i) N = length(x);
end total = 0;
for i=1:N
total = total + x(i)
Students: Try with different x vectors end
Flow Control
while loop We want to find for what value of x the function has its minimum value
x = -20:0.1:20;
y = 2.*x.^2 + 20.*x - 22;
plot(x,y)
grid Element-wise
multiplication
i=1;
while ( y(i) > y(i+1) ) (-5,72)
i = i + 1;
end
x(i)
y(i)
The minimum of the function
Whats next?
Learning by Doing!
Use the arrows keys to ”browse” in Decimal sign: Use ”.”– NOT ”,” !
previous commands used in the i.e. y=3.2 – not y=3,2
Command Window
Yes:
Use english names on variables, functions, files, etc. This is
a=2; No:
common practice in programming!
Use always variables – Do not use numbers directly in the b=4; y=2+4
expressions! y=a+b
Functions: clear
• Only ONE function in each File! Always include these clc
• The Filename (.m) AND the Name of the Function MUST be lines in your Script: close all
the same! …
Tips & Tricks Use help in order to find out how
to use a function in MATLAB. In
order to get help for the tf
function, type the following in the
Command window:
>>help tf
x = 2;
y = 2;
z = 3*x^2 + sqrt(x^2 + y^2)+ exp(log(x))
Hans-Petter Halvorsen
University of South-Eastern Norway
www.usn.no
E-mail: [email protected]
Web: https://www.halvorsen.blog