You are on page 1of 89

Mech 1820

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)

How to contact me:


By e-mail: hugh@acfr.usyd.edu.au
By web: www.acfr.usyd.edu/people
By Phone: 9351-5583
By Appointment: (use e-mail)

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

General Course Structure


Lectures
I will introduce you to computing in an engineering environment
We will use Matlab for this purpose (more later)
I will talk about the basics and do examples during lectures (I welcome questions)
You must reinforce this by reading books and doing the labs.
Lab Work
2-hour labs for every student, 1 per week for 10 weeks starting now (10 total).
You must do some preparation (see guidelines)
You must complete the lab during your assigned session.
You must attend your assigned laboratory session
Tutors look after labs and will only sign off during the lab
Assignment
A significant design project using Matlab.
Runs from week 10 to 13 inclusive.
Laboratory time is used for this assignment
Copying or sharing results will be severely penalised

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.

Other Good Books:


Engineering Problem Solving with Matlab, D.M. Etter, Prentice Hall. This is for
beginners only but has some good examples.
Mastering Matlab 5, D, Hanselman and B. Littlefield, Prentice Hall. This has all you will
ever need to know and but is mainly for advanced users.

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

In desperation, contact me. I am usually a nice person.

How to do well

Learn by doing. There is no other way of passing this course.

Do not be afraid to try things. Matlab is forgiving and helpful !

Read the notes and the books. Use help facilities.

Think !

In The Beginning

Things you need to know about computers:

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

Then we begin with Matlab

10

The Structure of the PC Lab and Connections

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

Essentially an interpreted language based on Matrices.

Originally Developed in the mid 1980s

Added to by many researchers and teachers over the past 15 years.

Available in a basic form on all platforms: PCs workstations, etc.

Student Edition available for approximately $95 and covers just about everything.

12

Why Use Matlab ?


Extremely powerful and simple environment for solving complex engineering problems.

A huge range of built-in functions from simple mathematical functions to symbolic


equation solvers.
Sophisticated built-in graphics from simple plotting to animated 3D graphics and Image
display.

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.

Typically a prototyping environment

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

Also variable assignment


>> a=10
>>b=5
>>c=a*b
Most obvious things work:
>>a=2.99e8
>>b=77e9
>>c=a/b

15

Basic Calculations

Basic Maths operations are as expected:


>>a=2
>>b=300
>>c=b^a
>>d=a+b
>>e=(a*b +c)/d
There are many basic built-in functions in Matlab:
>>f=cos(a)+sin(b)
>>g=sqrt(a^2+b^2)
>> who

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 column vector, or a [4,1] (row x column) matrix

b = (1 2 3) a row vector, or a [1,4] matrix


1 2 3 4

A = 5 6 7 8
9 0 1 2

a [3,4] matrix

An [m,n] matrix has m rows and n columns, with a total of m x n entries

17

Matrices and Arrays in Matlab I


A scalar number is really only a special case of a matrix
>> a=[10]
>>b=[2]
>>c=a+b
Matlab thinks only about matrices:
Row Vectors:
>>a=[10, 11]
>>b=[2, 3]
>>c=a+b
Or Column Vectors:
>> a=[10; 11]
>>b=[2; 3]
>>c=a+b

18

Matrices and Arrays in Matlab II


Or general arrays (matrices)
>>a=[1, 2; 3, 4; 5, 6]
>>b=[6, 5; 4, 3; 2, 1]
>>c=a+b
However
>> a=[10; 11]
>>b=[2, 3]
>>c=a+b
ERROR ! Matrix Dimensions must agree !
To add or subtract matrices, arrays must have compatible dimensions.
Note, the empty matrix
>> em=[ ]

19

General rule for Matrix Addition and Subtraction

Number of rows and columns in A and B must be the same:

a11
a
21
a31

a12
a22
a32

a13 b11 b12


a23 b21 b22
a33 b31 b32

b13 a11 b11


b23 = a21 b21
b33 a31 b31

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

Array and Matrix Operations

22

Matrix Multiplication: Multiplication by a Scalar


>>A=[1 2 3; 4 5 6]
>>K=5
>>B=K*A
>>C=A/32.1

a11 a12 a13 ka11 ka12 ka13


k a21 a22 a23 = ka21 ka22 ka23
a31 a32 a33 ka31 ka32 ka33
a11 a12 a13
a11 / k a12 / k a13 / k
a
k = a / k a / a / k
a
a
22
23
22
23
21
21

a31 a32 a33


a31 / k a32 / k a33 / k

23

General Matrix Multiplication


Not quite so straight forward. To multiply two matrices, the columns of the first matrix
must be equal to the rows of the second matrix, eg:

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]

Cij = [ Aik ] Bkj


[m, n] = [m, k ][k , n] i = 1,  , m, j = 1,  , n, k = 1,  k

24

Matrix Multiplication in Matlab


Square times Vector:
>>a=[1, 2; 3, 4]
>>b=[10; 11]
>>c=a*b
Rectangular works too
>> a=[1, 2, 3, 4; 5, 6, 7, 8]
>>d=a*b
Obvious mistakes:
>> e=b*a
ERROR ! Matrix Dimensions must agree !
Generally:
To add two matrices, they must have the same number of rows and columns
To multiply two matrices a*b, a must have the number of columns as there
are rows of b.

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:

You can miss out the commas when it is obvious


>>a=[1 2; 3 4]
You can split columns over lines to make it easy to read
>>b=[1 2 3 4;
5 6 7 8]
Or equally (dangerous):
>>b=[1 2 3 4
5 6 7 8]

You can continue rows too using ellipsis:


>> a=[1, 2, 3, 4, ...
5, 6, 7, 8]

27

More Matrices II:


You can prevent printing with a semicolon:
>> a=[10e-5 1.2345e3];

But the result is still there


>> a
You can put white space anywhere obvious
>>a=[1
5 4 3];

You can copy things easily


>>d=a

You can reassign things


>>a=d+a

28

More Matrices III:


You can print its value
>>a
>>d

You can find the size of a matrix easily:


>>size(a)
or
>> [rows, columns]=size(a)
>>size_of_a=size(a)
>>size_of_a
or even
>> fred=size(a)+size(b)

29

Big and Small Matrices I:


You can print a specific matrix element:
>>a(1,2)
Or you can assign it somewhere
>>abit=a(1,2)
Or you can assign it a value
>>a(1,2)=10
You can get a larger bit of a matrix:
>>a=[1 2 3 4; 5 6 7 8; 9 10, 11, 11];
>>b=a(2:4,2)
>>c=a(2,1:2)
You can get a whole row or column
>>b=a(:,2)
>>c=a(:,1)

30

Big and Small Matrices II:


Transposes are easy too (make rows in to columns)
>>a
>>b
>>c
You can build up matrices:
>>b=[a ; 13 14 15 16]
>>c=[a; a]
>>d=[b, b+b, b+b+b]

You can do it bit by bit:


>> e=[a(:,3), a(:,2), a(:,1)]

31

Big and Small Matrices III

But make sure you keep the dimensions correct ! :


>> f=[b,a]
Error ! Matrix Dimensions Must agree !

You can build up some simple vectors easily:


>>time=0:1:100
>>tick=0:0.1:10

or
>>tick=time/10

32

Saving and Loading I


You can save data to a file by typing
save [filename] [variable list]
For example:
>>save data1 a b;
The data is saved in special binary form in a file called data1.mat
To save all variables type:
>>save data1
Just typing save means all data stored in the file matlab.mat
You can save data in ascii (readable) form using:
>>save data1.dat a b /ascii
Note, the mat extension is not used in this case

33

Saving and Loading II

You can Load data too. To recover just type:


>>load data1
If you saved it in ascii with a dat extension you need to say so:
>>load data.dat
You can also load externally generated data:
>>load c_output.dat
Note: puts data in the matrix c_output

34

Formats and Display I

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

Other Options are:


Five significant figures in e format:
>> format short e
Fifteen figures in e format:
>>format long e
Also signs only:
>>format +
The fprintf command from C can also be used:
>>fprintf(I am %f years old\n,age)
Etc

36

Special Values
pi

automatic storage of 3.14

i,j

initially set as the square root of -1

inf matlab representation for infinity


NaN

Not-a-Number

clock

returns the current time and date

date

returns the current date

eps

the resolution of the current computer

ans

default location for the answer to a calculation

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)

A matrix of zeros (useful for initialisation)


>>a=zeros(10)
>>a=zeros(1,10)
>>a=zeros(b)

38

Special Matrices II

The identity matrix


>>a=eye(6)
>>a=eye(8,2)
>>a=eye(b)

Other interesting ones:


>>a=magic(4)
>> b=[1 2 3]
>>B=diag(b)

END OF SECOND LECTURE

39

Functions and Plotting

40

Common Functions
Matlab has many many built in functions:

Trigonometric: sin, cos, tan, acos, asin, atan, sec. Eg:


>>sin(4.567)
>>cos(2*pi*4.3)

General Functions: sqrt, log, log10, exp. Eg:


>>sqrt(2)
>>exp(3)

41

Common Functions
Numeric functions: abs, round fix, floor, sign, ceil. Eg:
>>round(2.645)
>>floor(2.645)

Also binary operations such as: atan2, rem, etc: Eg:


>>rem(101,3)

Take a look in help for a complete listing

42

Array Functions II

Most Matlab functions also work on vectors:


>>t=0:0.1:20
>>x=sin(2*pi*t);
>>y=cos(2*pi*t)
>>obvious=x.^2 + y.^2

And also on matrices:


>>a=[1 2; 3 4];
>>x=sin(a)
>>y=cos(a)
>>mag_t=abs(t);
Matlab does not distinguish between scalars and arrays

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

Changing the basics: Scaling:


axis([xmin xmax, ymin,ymax])
>>axis([0 2 -2 2])
>>ve=[-2 2 0 1]
>>axis(v)
Other bits:
>>axis(equal)
>>axis(normal)
Do help axis for all options.

47

Advanced Plotting II
Adding a title and labels:
>>title(A nice sine-wave)
>>xlable(Magnitude)
>>ylable(time)
>>text(20,0.5,A spot)

Maybe a grid too !


>>grid
Hold it for the next plot
>>hold on
>>plot(t,y)
>>hold off

48

Advanced Plotting III


Maybe makes some fancy legends
Clear the figure
>>clf
Generate a plot
>>plot(t,x,t,y)
>>legend(Cosine,Sine)
Use help legend to find options.
Other things about plots:
Scaling or rotating the drawing
Copying to a word document

49

Even More About Plotting


Changing colours and adding points:

You can change the default colour of a graph as follows:


>>plot(t,x,r,t,y,g)
This plots x in red and y in green.

You can mark data points to:


>>plot(t,x,x)
This plots x with crosses marking each data point.
You can change colour and markings in the obvious way:
>>plot(t,x,ro,t,y,gx)

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

There are other ways of plotting things.


>>t=0:0.1:10
>>x=exp(-t)+exp(-4t)
>>plot(t,x)
Not too interesting so try:
>>semilogx(t,x)
>>semilogy(t,x)
>>loglog(t,x)
Common in Engineering applications to use log plots to show orders of magnitude
variation.
Most common plot commands work with log plots. Eg axis, grid, colour, hold, etc.
>>grid

52

Weird Plots

Polar plots are also common


>>theta=t/3; % note in rads !
>>polar(theta,t)
>>title(My First Polar Plot)
>>grid
All in one go:
>> polar(theta*2,t); title(My Second Polar Plot); grid;
Bars and Stairs are also sometimes useful:
>>bar(t(1,1:20),theta(1,1:20))
>> stairs(t(1,1:20),theta(1,1:20))

53

The Final Word on 2D Plotting

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

END OF THIRD LECTURE

55

Systems of Linear Equations,


Matrix Multiplication and Division

56

Systems of Linear Equations I


Many engineering problems turn out to require the solution of sets of linear equations:

a11 x1 + a12 x2 + a13 x3 = b1


a21 x1 + a22 x2 + a23 x3 = b2
a31 x1 + a32 x2 + a33 x3 = b3

a11
a
21
a31

a12
a22
a32

a13 x1 b1
a23 x2 = b2
a33 x3 b3

These are naturally written down and solved as matrix equations

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

Systems of Linear Equations II


Solution Example:

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.0 cos 30o Ex = 0

80.0sin 30o + E y 20 30 = 0

59

Electrical Example of Equations


R1

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

Return to Array Operations I

Some arrays to start with:


>>a=[1 2; 3 4]
>>b=[5;6]
>>c=[7 8]

General Multiplication is ok (Keep dimensions consistent !):


>>dm=a*b
>>em=c*a
>>fm=c*b
>>gm=b*c
>>hm=em*a
Multiplciation by a scalar works too
>>ds=a*5
>>es=pi*b

61

Return to Array Operations II


Element by element operations (note the difference):
>>hm=em*a
>>he=em.*a

Addition and Subtraction:


>>da=b-c
>>fa=em+a
>>ga=5-a
Element by element addition and subtraction is just normal matrix addition and
subtraction.

62

Array Operations: Division

A vector or matrix divided (right) by a scalar:


>>dd=a/5
>>ed=b/2.345
Also left division
>>fd=5\c
Element by element division of a vector by a vector:
>>dd=a./em
>>ed=b./c
>>ed=a.\em

63

Array Operations: Division

General division is not so simple. Matlab assumes that the division is aimed at solving
either:
Ax=b
xA=b

as x=A-1 b (left division)


as x=bA-1 (right division)

For example (providing the inverse of a exists):


>> ds=c/a
>>es=b\a
This is what makes Matlab especially powerful: It can solve large systems of
simultaneous equations in a very transparent manner.

64

Array Operations: Division


However, it will also solve this system of equations when A is not square:
>>fs=1/b
>>gs=c\1
The meaning of these solutions is beyond what you need to know (this year at least)
Generally, you are better as follows:
>> Ai=inv(A);
>> eai=Ai*b;
Makes things clearer ! Take care with matrices.

END OF LECTURE FOUR

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

Now you can run your code


>>x=1 % set the value of x
>>eg1 % run the script file by just typing the name
>>f
% print the answer
Note that Matlab automatically found the script file. This is because you gave it a *.m
extension. Matlab always looks in the local directory for the function.
WARNING !! Do not give script files and variables the same name. Matlab gets
confused.

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

Matlab has six relational operators


Operator
<
<=
>
>=
==
~=

Interpretation
less than
less than or equal to
greater than
greater than or equal to
equal to
not equal to

Zero is logical false.


One is logical true.

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

Relational Operators III


As always, Matlab makes no distinction between scalars and arrays:

>> a=[2 4 6]; b=[3, 5, 1];


>> a<b
[1 1 0]
>>a ~= b
[1 1 1]

Relational operators work with any equal sized vectors or matrices.


The result of a relational operator is either true or false (1 or 0)

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

Zero is taken as logical false.


Any other number (including negative numbers) are taken as logical true.

73

Logical Examples I

>>a=1; b=1; c=0


>>a&b
ans=1
>>~a
ans=0
>>a&b&c
ans=0
>>a&b&(~c)
ans=1
>>(a&b)|(a&c)
ans=1
Dont make things to complexit can be confusing !

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]

Note that Matlab treats any non-zero number as true:


Thus:
>> a=[1 -2 4]; b= [ 0 2 3];
>> a&b
[0 1 1]
However, it is of course more normal to deal with vectors consisting only of 1 and 0:

75

Logical Examples III


>> a=[2 4 6]; b=[3 5 1]; c=[4 2 2];
>> a<b & b<c
[1 0 0]
Any combination is valid eg:
>> ~(b==c | b<a)
Although often a good idea to use parentheses to make sure the logic is correct:
>> a>b&b>c
>>a>b&c

76

Control Flow

Matlab has three decision-making or control-flow structures:

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

FOR LOOPS III

For loops can be nested in the obvious way:


>> for n = 1:5
for m = 5:-1:1
A(n,m)=n^2+m^2;
end
disp(n)
end

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

For loops execute a group of statements a fixed number of times.


While loops execute a group of statements an indefinite number of time:
while {expression}
[Commands]
end
where expression is any logical expression evaluating to true or false. For example:
A method of computing MATLAB resolution.
>> num=0; EPS=1;
>> while (1+EPS)>1
EPS=EPS/2;
num=num+1;
end
>> num
num= 53
>> EPS=2*EPS
EPS= 2.2204e-16

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

IF-THEN-ELSE Statements III


Legal ways of breaking from loops:
>>EPS=1;
>> for num=1:1000
EPS=EPS/2;
if (1+EPS) <= 1
EPS=EPS*2;
break;
end
end
>>EPS
EPS=2.2204e-16
>>num
num=53
>>

86

First Big Example


% MMONO Test for a monotic vector.
% when X is a vector:
% 2 if X is strictly increasing
% 1 if X is non decreasing
% -1 if X is non increasing
% -2 if X is strictly decreasing
% 0 otherwise
x=x(:);
% make x a column vector
y=diff(x); % find differences between consecutive elements
if all(y>0)
% test for strict first
f=2;
elseif all(y>=0)
f=1;
elseif all(y<0) % test for strict first
f=-2;
elseif all(y<=0)
f=-1;
else
f=0;
end
f % print the result

87

First Big Example

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

xmin, xmax, tic, and afunction

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

You might also like