MANU2206 Week03 PDF
MANU2206 Week03 PDF
MANU2206 Week03 PDF
Dr. Tu Le
School of Engineering
RMIT University, Victoria, Australia
Email: tu.le@rmit.edu.au
Plotting Variables in MATLAB
• The command
>>plot(x,y);
• plots y values versus x values, if x and y are
both vectors or row matrices with the same
lengths.
• Plotting several curves simultaneously:
>>plot(x1,y1,x2,y2,x3,y3);
2
Plotting Variables in MATLAB
3
Plotting Variables in MATLAB
12
x=(0:0.1:5)'; 10
y=2*x+3; 8
n=2*rand(size(x))-1;
6
y=y+n;
4
plot(x,y,'.');
2
0 0.5 1 1.5 2 2.5 3 3.5 4 4.5 5
5
6
Linear Regression
• Example (Continued):
>> X = [x ones(size(x))];
>> A = X\y 14
A = 12
2.0107 10
2.9766 8
7
MATLAB Scripts
9
FOR loops
10
FOR loops
11
The golden rectangle
A golden rectangle is a
rectangle whose side
lengths are in the golden
5−1
ratio:
2
12
The golden ratio
13
The golden ratio
© Depositphotos.com
14
FOR loops
15
FOR loops
1
Ratio of terms fn-1/fn
0.8
0.6
0.4
0.2
0
0 5 10 15 20
n
16
Logicals in MATLAB
>> x=pi
x = 3.1416
>> x ~= 3, x ~= pi
ans = 1
ans = 0
18
Logicals in MATLAB
19
While Loops
20
While Loops
• Example: Find the approximate root of the equation 𝑥 =
cos 𝑥 .
• We can do this by making a guess 𝑥1 = 𝜋/4, say, then
computing the sequence of values 𝑥𝑛 = cos 𝑥𝑛−1 for 𝑛 =
2, 3, … and continuing until the difference between two
successive values 𝑥𝑛 − 𝑥𝑛−1 is small enough.
• Contents of the script:
• Run it and you will xold = pi/4; n = 1; d = 1; xnew
= xold;
see MATLAB while d > 0.001 & n < 20,
echoing: xold = xnew;
n = 14 n = n+1; xnew = cos(xold);
d = abs(xnew-xold);
xnew = 0.7388 end
[n xnew d]
21
IF Statements
22
IF Statements
• An example:
n = sum(1:5:1000);
if n>1e5,
m = n;
end
• What is the value of m if n≤1e5?
23
24
IF Statements
• An example (continued):
n = sum(1:5:1000);
if n>1e5,
m = n;
else
m = 0;
end
25
MATLAB Functions
26
MATLAB Functions
• General form:
function [out1, out2, ...] = myfun(in1, in2, ...)
statements
⋮
end
27
MATLAB Functions
Example:
The following function inputs three sides of a triangle and outputs its
perimeter and area:
Formulas: For sides a, b, c, the perimeter is S = a+b+c and the area
𝑆
is given by 𝐴 = 𝑝(𝑝 − 𝑎)(𝑝 − 𝑏)(𝑝 − 𝑐) where 𝑝 = .
2
29
Simulink
30
Simulink
31
Simulink interface
32
Simulink
33
Simulink
34
Simulink
35
Simulink
36
Simulink
37
Simulink
38
Simulink
39
Simulink
40
Simulink
41
Simulink
42
Simulink
43
Simulink
44
Simulink
45
Simulink
46
Simulink
47
Simulink
48
Simulink
49
Simulink
50
Simulink
51
Simulink
52