Académique Documents
Professionnel Documents
Culture Documents
Introduction to Matlab
Who am I ?
Hugh Durrant-Whyte
Professor of Mechatronics
Director, Australian Centre for Field Robotics (ACFR)
School of Aerospace, Mechanical and Mechatronic Engineering (AMME)
Administration
Course web page:
http://www.acfr.usyd.edu.au/teaching/1st-year/Matlab/index.html
I put everything; lectures, labs, questions, answers, grades,.on the web page.
I also make extensive use of e-mail
General:
Lectures: Tuesday 1100, Carslaw 159
Computer Laboratories and assigned time with tutors:
In School PC lab, 2 hours/week for each student.
Wednesday, 2pm-4pm, 4pm-6pm, Thursday 2pm-4pm, 4pm-6pm.
Times are allocated by the University (not by me !)
Course Grading:
60% of marks on Laboratory work
40% of marks on Final Assignment
You must get at least half marks in the major assignment
No Final Examination
Books ?
The Student Edition of Matlab (Version 6.x), Prentice Hall. This comes with a CD of
Matlab (student edition) and the Matlab manual so you can use it at home. Cost is
approximately $100.
Course Objectives
Goals:
1. Know how to use a computer to solve engineering problems.
2. Become familiar and competent in the use of Matlab for solving engineering
problems
3. Develop your ability to lay-out and solve engineering problems
Not Goals:
1. Be an amazing programmer
2. Teach you about maths
My Expectations of You
Attend Lectures and Tutorials. Listen and Ask Questions if you do not understand.
Be responsible for your own learning and make an effort to learn.... I have already
passed this course !
Be reasonably mature: do not use your mobile phone in lectures, abuse the computer
system, copy other students assignments, etc.
Keep up to date with lab work. Submit assignments on time. Talk to the tutors
How to do well
Think !
In The Beginning
1) How to log-on
2) Understanding the file and directory structure
3) How to set up your password and file space
4) How to start-up Matlab
5) How to down-load useful stuff from the web
10
Data
iM ac
Telephone
Data
Ethernet
Your Home
ITS
PC Lab
File Server
Welcome to the School of Aerospace, Mechanical and Mechatronic Engineering for 2002
We have been making some changes to the way that student data is stored on UGLABSERV01, your data server. The
main change is that data must now be stored using a FTP client software package such as WS_FTP which is installed on all
of the PCs in all the computer labs in this school. The main benefit of this is to allow you to upload or download data from
your home PC (ONLY IF YOU USE THE UNIVERSITY AS YOUR INTERNET SERVICE PROVIDER).
To use the WS_FTP package, follow the steps below;
1.
Left click on Start, Programs and WS_FTP
2.
Left click on the New button
3.
Ensure that the session properties are as per the image left;
Profile Name:
IP Address of Server:
Host Type:
Set to Automatic detect
User ID (in PCLAB Domain)
Set to your SID
Your password in the
PCLAB Domain
Do not tick anonymous
Left click Apply
Left click OK
Once you click OK the program will send you directly to your own personal directory. These setting for WS_FTP also work for your
home computer, provided that you have an account with ITS.
If you are still having difficulties please contact, Paul Briozzo in room S319a or via email on paulb@aeromech.usyd.edu.au
11
Matlab
A product of Mathworks Inc.
Matlab=Matrix Laboratory
Student Edition available for approximately $95 and covers just about everything.
12
Simple to develop complex software systems: eg: F14 flight control system.
Widely used in almost all areas of Engineering for teaching, research and product
development.
13
Getting Started
The prompt:
>>
Matlab it is an interactive language much like Basic. What you type at the screen is
what you get. You can write Matlab programmes (we will). However, these are not
compiled like C, Java or Fortran.
Matlab is very forgiving.it tells you when and what you get wrong. SO do not be afraid
to try things.
Now just type:
>>help <command>
>> save <file>
>> load <file>
>> who
>>quit
14
Numbers
Works with basic numbers as a calculator:
>>10*5
>>5/10
15
Basic Calculations
16
Arrays of Numbers
Matlab treats every variable as an array or Matrix
What is a scalar, a vector, a matrix?
a = 1.0
1
2
a=
3
4
a scalar
A = 5 6 7 8
9 0 1 2
a [3,4] matrix
17
18
19
a11
a
21
a31
a12
a22
a32
a12 b12
a22 b22
a32 b32
a13 b13
a23 b23
a33 b33
20
Advanced Bit !
Matlab allows you to create Matrices easily:
>>t=0:0.1:10;
>>size(t)
Then it can manipulate them as if they were scalars (but according to matrix rules !)
>>x=cos(t);
>>y=sin(t);
>>plot(t,x,)
>>title(My first Plot !!)
The reason Matlab is widely used is that you can do just about anything with relatively
little programming.
END OF FIRST LECTURE
21
22
23
1 2 3 a x 1* a + 2* b + 3* c 1* x + 2* y + 3* z
4 5 6 b y = 4* a + 5* b + 6* c 4* x + 5* y + 6* z
7 8 9 c z 7 * a + 8* b + 9* c 7 * x + 8* y + 9* z
[3,3]
[3, 2]
[3, 2]
In General:
[C] = [ A ][B]
24
25
WARNING !!!!
Matrix multiplication is as much as you need to know at this stage (about matrices)
Matrix division (matrix inversion) is non-trivial so be careful about typing
>>C=A/B
when A and B are matrices.
If, what you really wanted was all the elements in A to be multiplied (divided) by all the
elements in B, then Matlab has a special syntax:
>>C=A.*B
>>D=A./B
Note the dot. In this case A and B must have the same dimensions.
Dont panic . More detail on this later.
26
More Matrices I:
27
28
29
30
31
or
>>tick=time/10
32
33
34
Occasionally You will need to Change the Format or Display of the Basic Matlab
Output.
The Command format does this.
To get lots of numbers (15 significant figures) type:
>>format long
When you have had enough type
>> format short
This returns to the usual 5 significant figure format
35
36
Special Values
pi
i,j
Not-a-Number
clock
date
eps
ans
37
Special Matrices
A number of functions exist for generating special matrices:
A matrix of 1s:
>>a=ones(4)
>>a=ones(3,2)
>>b=[1 2; 3 4]
>>a=ones(b)
38
Special Matrices II
39
40
Common Functions
Matlab has many many built in functions:
41
Common Functions
Numeric functions: abs, round fix, floor, sign, ceil. Eg:
>>round(2.645)
>>floor(2.645)
42
Array Functions II
43
Array Functions
However, when multiplying or dividing matrices you must take care:
>>right_answer=x.^2 + y.^2
>>wrong_answer=x^2 + y^2
because the square of a matrix is not the same as a matrix of squares !
Some care needs to be taken to say what you mean as some things have a matrix
definition different from a scalar definition. Eg:
>>sqrt_t=sqrt(t)
>>sqrt_a=sqrt(a) % some care here !
Likewise some things you will not have seen before:
>>de=exp(a)
>>ee=log(de)
44
Complex Numbers
Matlab deals with complex numbers in a transparent manner:
>>j
>>a=2+3j
>>b=4+5j
>>c=a/b
Also with vectors (and matrices)
>>t=-2:0.1:2
>>x=sqrt(t)
Note: Once an element is complex, it remains complex, even if the imaginary part goes
to zero.
Functions:
>>abs(b)
>>real(b)
>>imag(b)
>>mag(b)
>>angle(b)
45
Basic Plotting
Matlab has extensive facilities for plotting and graphically analysing data.
Here we will look at basic plotting capabilities.
First some data to play with
>>t=0:0.1:10
>>x=sin(2*pi*t)
>>y=cos(2*pi*t)
Simple plot command: Plots vector against vector index
>>plot(x)
Plot of x against time (vectors must be of the same length).
>>plot(t,x)
>>plot(x,y)
Multiple plots
>>plot(t,x,t,y)
46
Advanced Plotting I
47
Advanced Plotting II
Adding a title and labels:
>>title(A nice sine-wave)
>>xlable(Magnitude)
>>ylable(time)
>>text(20,0.5,A spot)
48
49
50
Colour
The complete spec is:
y yellow
m magenta
c cyan
r red
g green
b blue
w white
k black
. point
o circle
x x-mark
+ plus
- solid
* star
: dotted
-. dashdot
-- dashed
51
Fancy Plots
52
Weird Plots
53
You can also generate Multiple Plots in two ways, by generating separate windows or
by splitting an existing window:
A new Window:
>>figure(2)
>>plot(t,x)
>>figure(1)
>>plot(t,y)
Note the idea of an active window
54
Window Splitting:
Splitting: Specify a number mnp, where the plot is split in to m*n subplots and p is the
sublot on which to start drawing.
>>t=0:0.1:10;
>>x=sin(t);
>>y=cos(t);
>>subplot(211)
>>plot(t,x); title(Sine-Wave);
>>subplot(212)
>>plot(t,y); title(Cosine-Wave);
55
56
a11
a
21
a31
a12
a22
a32
a13 x1 b1
a23 x2 = b2
a33 x3 b3
x = A 1b = A \ b
Ax = b
a11
A = a21
a31
a12
a22
a32
a13
x1
b1
a23 , x = x2 , b = b2
x3
b3
a33
57
10 x + 9 y + 6 z = 1
7 x + 8 y 3 z = 3
x + 10 y 4 z = 9
In Matlab:
>> A=[10 9 6; 7 8 -3; -1 10 -4];
>> b=[1;-3;9];
>> x=A\b
x=
-1.3274
1.0743
0.7675
10 9 6 x 1
7 8 3 y = 3
1 10 4 z 9
58
Statics Example
T
30o
5m
5m
5m
5m
5m
30kN
5m
5m
20kN
M = 0:
F = 0:
F = 0:
Ex
Ey
5T 20(5) 30(10) = 0
80.0sin 30o + E y 20 30 = 0
59
i2
R2
i1
+
-
R3
R4
i3
R5
+ R 2 (i1 i2 ) + R 4 (i1 i3 ) = 0
R1 i2
+R 3 (i2 i3 ) +R 2 (i2 i1 ) = 0
R 3 (i3 i2 )
+R 5 i3
+R 2 (i3 i1 ) = 0
60
61
62
63
General division is not so simple. Matlab assumes that the division is aimed at solving
either:
Ax=b
xA=b
64
65
Script Files I
Quite often you want to reuse bits of code over again. One way to do this is to use a
script file.
A script file is simply a listing of Matlab commands that you might otherwise have typed
at the keyboard.
Start up the built-in Matlab editor. Type in the following:
numerator=x.^3-2*x.^2 + x - 6.3;
denominator=x.^2+0.05005*x-3.14;
f=numerator./denominator;
Note that the editor recognises the syntax. This might help you not make mistakes.
Save this in a file called eg1.m (the m extension is the important bit).
66
Script Files II
Now start up matlab and check you are in the right directory
>>pwd
>>cd m:
>>cd teaching/matlab
67
Script Files II
We set up our script function so that it could also use arrays. Thus:
>>x=0:0.1:10
>>eg1
>>plot(x,f)
>>title(Great Looking Plot)
We could put all of the above into a slightly longer script fileeg2:
numerator=x.^3-2*x.^2 + x - 6.3;
denominator=x.^2+0.05005*x-3.14;
f=numerator./denominator;
plot(x,f)
title(Great Looking Plot)
68
Flow Control
A basic problem now is that a script file is just a list of instructions. What we need is to
be able to change the flow of instructions depending on the values of the variables. To
do this, we need to
a) Test variables: is a greater than b ? Is c equal to 105 ? etc.
b) To do something (other than the next instruction) depending on the outcome of a
test: if a is greater than b then plot a, else plot b. While c is greater than 0 subtract
one.
Matlab provides both tests and flow control structures. With these we will be able to
write proper intelligent programmes.
69
Relational Operators I
Interpretation
less than
less than or equal to
greater than
greater than or equal to
equal to
not equal to
70
Relational Operators II
Logical expressions may be formed as follows:
>>x=10; y=11;
>>x>y
ans=0
>> x<y
ans =1
>>x ~= y
ans=1
>> y=10;
>> x>y
ans=0
>>x>=y
ans=1
>> x==y
ans=1
71
72
Logical Expressions
Matlab can also do logical manipulation (combinations of true and false)
Matlab has three logical operators:
Logical Operator
and
or
not
Symbol
&
|
~
73
Logical Examples I
74
Logical Examples II
Of course, arrays (of the same dimension) work also
>> a=[1 0 1]; b=[1 1 1]; c=[1 1 0];
>>a&b
ans=[1 0 1]
>>a&c
ans=[1 0 0]
>> ~c
ans=[0 0 1]
75
76
Control Flow
For Loops
While Loops
If-Then-Else structures
We will look at each of these in turn
Most of these expressions use the logical operators described previously.
77
FOR LOOPS I
For Loops: A simple example
>>for n=1:10
x(n)=sin(n*pi/10);
end
>>
Note the use of the end statement.
The assignment n=1:10 is a general array assignment
>>n=1:10
78
FOR LOOPS II
Other array assignments work too:
>> for n=1:2:20
y(n)=sin(n*pi/10);
end
>>
or even
>>data=[3 9 45 6; 7 16 -5 5]
>>for n=data
x=n(1)-n(2);
end
>>
Generally:
for n=vector
[ calculations involving nth element of vector]
end
79
80
FOR LOOPS IV
You can not terminate the loop by resetting the index
>>for n=1:10
x(n)=sin(n*pi/10);
n=10; % this has no effect at all
end
>>
For loops should be avoided whenever there is an equivalent array way of doing it:
>>n=1:10;
>>x=sin(n*pi/10);
To maximise speed, space should be allocated at the start:
>>z=zeros(1,10); % preallocate space
>>for n=1:10
z(n)=sin(n*pi/10);
end
>>
81
WHILE LOOPS
82
IF-THEN-ELSE Statements I
Simple if statement:
if {expression}
[commands]
end
Example:
>>apples=10;
>>cost=apples*25
cost=250
>> if apples>5
% give 20% volume discount
cost=(1-20/100)*cost;
end
>>cost
cost=200
83
IF-THEN-ELSE Statements II
Else statements:
if {expression}
[commands]
else
[commands]
end
Example:
>>if apples > 5
cost=(1-20/100)*apples*cost_per_apple;
else
cost=apples*cost_per_apple;
end
84
IF-THEN-ELSE Statements
General IF-ELSEIF-ELSE:
if {expression1}
[commands 1]
elseif {expression2}
[commands 2]
else if {expression 3}
[commands 3]
............................................
else
[commands n]
end
85
86
87
>>x=1:12
ans=2
>>x=[1:12 12 13:14];
ans=1
88
Second Example
% script file to compute the zeros of a function
% over the range xmin to xmax
%
% user must define
x=xmin:tick:xmax;
y= eval(afunction);
[rows,cols]=size(y);
k=1;
for j=2:cols
% code to see if y has changed sign
% and therefore passes through zero
if (y(j)>0)&(y(j-1)<0) % change from negative to positive
z(k)=x(j) + (x(j)-x(j-1))/2;
k=k+1;
elseif (y(j)<0) & (y(j-1) >0) % change from positive to negative
z(k)=x(j) + (x(j)-x(j-1))/2;
k=k+1;
end
end
END OF LECTURES 5 and 6