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

Introduction To MATLAB - Overview

Here are the steps to evaluate this function for x from -10 to 10: 1) Define the x values: >> x = -10:10 2) Calculate y(x) using element-wise operations: >> y = 2.*x.^2 + 3.*x + 1 3) Display x and y(x) in a table: Index x y(x) 1 -10 121 2 -9 108 ... ... ... 11 10 221 Students: Try running this code!

Uploaded by

Baha Hasan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
35 views

Introduction To MATLAB - Overview

Here are the steps to evaluate this function for x from -10 to 10: 1) Define the x values: >> x = -10:10 2) Calculate y(x) using element-wise operations: >> y = 2.*x.^2 + 3.*x + 1 3) Display x and y(x) in a table: Index x y(x) 1 -10 121 2 -9 108 ... ... ... 11 10 221 Students: Try running this code!

Uploaded by

Baha Hasan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 52

Quick Start Tutorial

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

For Loop for n=1:6 % n = model order

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

• The MATLAB Environment (IDE)


• MATLAB Basics
The MATLAB Environment (IDE)

Working in the Development Environment

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

Getting Started with MATLAB

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!

Hit “ENTER” in order to


execute a command

Use “Arrow Up” in order to


browse through old Commands
(“Command History”)
MATLAB Basics
MATLAB is case sensitive! The variables x and X are not the same.

Students: Try these examples


>> x=5;
>> X=6; >> x=3
>> x+X x =
3
ans =
11 >> y=4;
>>

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

The “clear” command deletes all


>> clear existing variables” from the memory
>> clc
The “clc” command removes everything
from the Command Window
clc – Clear Command Window
>> clear x
Only clear the variable “x”

Students: Try these commands


MATLAB Basics
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
>> r=5; >> z1=3+3i;
>> A=pi*r^2 >> z2=3+5i;
>> a=2;
>> z = z1+z2
A = z = >> b=0;
78.5398 6.0000 + 8.0000i >> a/b
Students: Try these examples
MATLAB Basics Mathematical Expressions
Students: Try this example
MATLAB
log(x)
log10(x)
>> x=2;
>> y=3*x+2/2 sqrt(x)
y =
7 exp(x)
>> y=(3*x+2)/2
y = x^2
4 Which are correct?

Students: Calculate this expression, try with different


values for x and y
MATLAB Basics
Students: Calculate this expression, try with different values for 𝑥 and 𝑦

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!

Self-paced Tutorials with lots of


Exercises and Video resources

Do as many Exercises as possible! The only way


to learn MATLAB is by doing Exercises and
hands-on Coding!!!
Lesson 2
• Vectors & Matrices
• Plotting
Vectors & Matrices

Working with Arrays

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

Students: Try these examples


>> a = [1: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

Students: Try these examples Etc.


Vectors
Given the following Rain Data for a given Week (Monday to Sunday):
Day Rain Amount We define the Data in MATLAB like this:
Monday 2,1 mm
>> x = [2.1, 10, 9.7, 6.2, 2.5, 0, 8.5]
Tuesday 10 mm
Wednesday 9,7 mm
What is the Average Rain Amount this Week?
Thursday 6,2 mm
Friday 2,5 mm In MATLAB we can use the ”mean” function:
Saturday 0 mm >> mean(x)
Sunday 8,3 mm ans = 5.5714
We can define a variable, e.g.:
>> mean_value_week = mean(x)
mean_value_week = 5.5714

Students: Try these examples


Given the following function:
Vectors
𝑦 𝑥 = 2𝑥 2 + 3𝑥 + 1 where: −10 ≤ 𝑥 ≤ 10
Index x y(x)

>> x=-10:10 Note how we have used .* and .^


1

2
-10

-9
171

136

>> y=2.*x.^2 + 3.*x + 1 .* each element-wise


3 -8 105

4 -7 78
y = Multiplication 5 -6 55

171 136 105 78 6 -5 36

55 36 21 10 3 .^ each element-wise Power 7

8
-4

-3
21

10

0 1 6 15 28 What is 𝑦 3 =? 9

10
-2

-1
3

45 66 91 120 153 >> y(14) 11 0 1

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

Students: Try these 18 7 120

>> y = 2*x^2 + 3*x + 1 19 8 153

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

or: Try these examples


>> A = [1, 2; 3, 4] >> B+C
>> B-C
A = 1 2 >> B/C
>> B*C
3 4
>> B.*C
>> B'*C
...
Given the following matrices: Matrices

Define the matrices and try these examples

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

Using Basic Plotting Functions

http://www.mathworks.com/videos/using-basic-plotting-functions-69018.html
Plotting
>> x = 0:0.1:2*pi;
>> y = sin(x);
>> plot(x,y)

Students: Try this example

Students: Try also these examples:


>> x = 0:0.1:2*pi;
>> y = sin(x);
>> y2 = cos(x);
>> plot(x,y, x,y2)

...
>> 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

Given the following function (−10 ≤ 𝑥 ≤ 10 ):

𝑦 𝑥 = 2𝑥 2 + 3𝑥 + 1

Students: Plot this function


Use the Plot to find out:
- For which value of 𝑥 is 𝑓(𝑥) = 0?
- What is 𝑓(5) =?
>> x=0:0.1:2*pi;
Plotting Subplot >>
>>
y=sin(x);
y2=cos(x);
>> y3=tan(x);
Students: Try these examples
>> subplot(3,1,1)
>> x=0:0.1:2*pi; >> plot(x,y)
>> y=sin(x); >> subplot(3,1,2)
>> y2=cos(x); >> plot(x,y2)
>> subplot(3,1,3)
>> subplot(2,1,1) >> plot(x,y3)
>> plot(x,y)
>> x=0:0.1:2*pi;
>> y=sin(x);
>> subplot(2,1,2) >> y2=cos(x);
>> plot(x,y2) >> y3=tan(x);
>> y4=atan(x);
>> subplot(2,2,1)
>> plot(x,y)
>> subplot(2,2,2)
>> plot(x,y2)
>> subplot(2,2,3)
>> plot(x,y3)
>> subplot(2,2,4)
>> plot(x,y4)
Whats next?
Learning by Doing!

Self-paced Tutorials with lots of


Exercises and Video resources

Do as many Exercises as possible! The only way


to learn MATLAB is by doing Exercises and
hands-on Coding!!!
Lesson 3

• Scripts (m-files)
• User-defined Functions
Scripts (m-files)

Writing a MATLAB Program

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

You Create the Function in the Editor


Return value

You Use the Function in the Command


Window or in a Script

function output = function_name(input)


Students: Try this example
User-defined Functions
Example: Convert from Celsius to Fahrenheit

Students: Create a User-defined Function that converts from


Temperature in Celsius to Temperature in Fahrenheit

Try the function in a Script like this:

Try the function in the Command window like this:

>> Tc = 20;
>> Tf =
fahrenheit(Tc)

Tf =

68 You need to create


this function
User-defined Functions
clear
Solutions: Convert from Celsius to Fahrenheit clc

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!

Self-paced Tutorials with lots of


Exercises and Video resources

Do as many Exercises as possible! The only way


to learn MATLAB is by doing Exercises and
hands-on Coding!!!
Lesson 4
• Flow Control
–if...elseif...else
–while
–switch...case
Flow Control
Flow Control:
• if-elseif-else statement
• switch-case-otherwise statement
Loops:
• for Loop
• while Loop

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

n=2; Note! You have to use if n==1


and NOT if n=1
if n==1
disp('n=1')
elseif n==2 Operator Description
disp('n=2') < Less Than
elseif n==3 <= Less Than or Equal To
disp('n=3')
> Greater Than
else
>= Greater Than or Equal To
disp('n is not 1, 2 or 3')
== Equal To
end
~= Not Equal To

Students: Try the different operators


Flow Control
switch-case-otherwise
Run the Script several times with different
Students: Try this example values of n and see what happens

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

Students: Try this example.


Try also with other 2.degree functions
clear
clc

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!

Self-paced Tutorials with lots of


Exercises and Video resources

Do as many Exercises as possible! The only way


to learn MATLAB is by doing Exercises and
hands-on Coding!!!
Tips & Tricks
Use Comments (%)
% This is a comment
Tips & Tricks
x=2; % Comment2
y=3*x % Comment3 DO NOT use ”spaces” in Filename or names that
are similiar to built-in functions in MATLAB!
- but they have to make sense!

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

A Golden Rule: One Task – one m file, i.e. Mathematical expressions:


DON’T put all the Tasks in one single m file!! The following applies in MATLAB

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

You might also like