Você está na página 1de 120

EGYPTIAN ACADEMY OF

ENGINEERING & ADVANCED


TECHNOLOGY
(EAE&AT)

MATLAB / SIMULINK summer training


course

Summer 2016

EGYPTIAN ACADEMY OF
ENGINEERING & ADVANCED
TECHNOLOGY
(EAE&AT)

MATLAB / SIMULINK SUMMER


TRAINING COARSE

Page:2

Contents
Lesson
no.
1

5
6

7
8
9

Title
Basic MATLAB features

Vectors and matrices


..
Built-in functions ..
..
Arithmetic Operators ..
Relational
Operators

Logical
Operators

Solving algebraic equations (polynomials):


( Single equation , System of equations & Curve fitting
..
Solving differential equations:
1- First order differential equations
.....
2- Second and higher order differential
equations ..
3- System of differential equations

Laplace Transformation
.
Programming using MATLAB (M File).
..
Conditional Execution

Loops
.
Plotting 2-D graphs
.
Plotting 3-D graphs

Introduction to Simulink
.
Conditional
statements
using
Simulink
.
Loops using Simulink
.
Choosing
an
equation
solver
..
Creating
Graphical
User
Interfaces

Pag
e
3
5
12
22
22
24
30

37
38
39
40
45
51
54
58
69
82
100
103
108
113

EGYPTIAN ACADEMY OF
ENGINEERING & ADVANCED
TECHNOLOGY
(EAE&AT)

MATLAB / SIMULINK SUMMER


TRAINING COARSE

Page:3

EGYPTIAN ACADEMY OF
ENGINEERING & ADVANCED
TECHNOLOGY
(EAE&AT)

MATLAB / SIMULINK SUMMER


TRAINING COARSE

Page:4

Lesson 1
Objectives:
MATLAB Basics
- The basic features.
- Vectors and matrices.

Material:

What is MATLAB?
MATLAB is a high-performance language for technical computing. It integrates
computation, visualization, and programming in an easy-to-use environment where
problems and solutions are expressed in familiar mathematical notation.
MATLAB, which stands for MATrix LABoratory, is a state-of-the-art mathematical software
package, which is used extensively in both academia and industry. It is an interactive
program for numerical computation and data visualization, which along with its
programming capabilities
provides a very useful tool for almost all areas of science and engineering.

Getting started with MATLAB:


Start Programs MATLAB7.0 MATLAB 7.0
Or double-click the icon on the desktop.

The MATLAB prompt () will be used to indicate where the commands are entered.
Anything you see after this prompt denotes user input (i.e. a command) followed by a
carriage return (i.e. the enter key). Often, input is followed by output so unless
otherwise specified the line(s) that follow a command will denote output (i.e. MATLABs
response to what you typed in). MATLAB is case-sensitive, which means that a + B is not
the same as a + b. Different fonts, like the ones you just witnessed, will also be used to
simulate the interactive session.
The command window is the primary place where you interact with Matlab. This window has
an
appearance as shown below.

1. Simple Math

EGYPTIAN ACADEMY OF
ENGINEERING & ADVANCED
TECHNOLOGY
(EAE&AT)

Let us start with something


do simple math. such as

MATLAB / SIMULINK SUMMER


TRAINING COARSE

Page:5

simple, just like a calculator, Matlab can

First we start with numerical that is using the MATLAB as calculator. You can use + to add, - to
subtract, * to multiply, / to divide and to exponentiation. For example,
>> 3^2 - (5 + 4)/2 + 6*3
ans =
22.5000

MATLAB prints the answer and assigns the value to a variable called ans.
If you want to perform further calculations with the answer, you can use the variable ans rather than retype the
answer. For example, you can compute the sum of the square and the square root of the previous answer as
follows:
>> ans^2 + sqrt (ans)
ans =
510.9934
Observe that MATLAB assigns a new value to ans with each calculation.

To do more complex calculations, you can assign computed values to variables of your choosing. For
example,
>> u = cos (10)
u=
-0.8391
>> a=3; b=5; a+b; c = a*b
ans =
8
c=
15

2. Vectors and matrices:

Defining a row vector with components the numbers 1, 2,3, 4, 5 and assigning it a variable name, say x.

>> x = [1 2 3 4 5]
x =

EGYPTIAN ACADEMY OF
ENGINEERING & ADVANCED
TECHNOLOGY
(EAE&AT)

MATLAB / SIMULINK SUMMER


TRAINING COARSE

Page:6

Note that we used the equal sign for assigning the variable name x to the vector, brackets to enclose its entries
and spaces to separate them. We could have used commas ( , ) instead of spaces to separate the entries, or even a
combination of the two. The use of either spaces or commas is essential!
>> y = [6;7;8;9;10]
y =
6
7
8
9
10
>> y = [6,7,8,9,10]
y =
6

10

First, note that to take the transpose of a vector (or a matrix for that matter) we use the single quote ( ').
>> y'
ans =
6
7
8
9
10
>> u = [0:8]
u =
0

Here we specified the first entry 0 and the last entry 8, separated by a colon ( : ). MATLAB automatically filledin the (omitted) entries using the (default) increment 1. You could also specify an increment as is done in the next
example.
>> v = [0:2:8]
v =
0

Here we specified the first entry 0, the increment value 2, and the last entry 8. The two colons ( :) tell
MATLAB to fill in the (omitted) entries using the specified increment value.
MATLAB will allow you to look at specific parts of the vector. If you want, for example, to only
look at the first 3 entries in the vector v,
>> v(1:3)

EGYPTIAN ACADEMY OF
ENGINEERING & ADVANCED
TECHNOLOGY
(EAE&AT)

MATLAB / SIMULINK SUMMER


TRAINING COARSE

Page:7

ans =
0

Note that we used parentheses, instead of brackets, to refer to the entries of the vector. Since we omitted the
increment value, MATLAB automatically assumes that the increment is 1. The following command lists the first
4 entries of the vector v, using the increment value 2 :
>> v(1:2:4)
ans =
0

Defining a matrix is similar to defining a vector. To define a matrix A, you can treat it like a column of
row vectors. That is, you enter each row of the matrix as a row vector (remember to separate the entries
either by commas or spaces) and you separate the rows by semicolons ( ; ).

>> A = [1 2 3; 3 4 5; 6 7 8]
A =
1
3
6

2
4
7

3
5
8

We can avoid separating each row with a semicolon if we use a carriage return instead. In other words,
we could have defined A as follows
>> A = [
1 2 3
3 4 5
6 7 8]
A =
1
3
6

2
4
7

3
5
8

You can refer to a particular entry in a matrix by using parentheses. For example, the number 5 lies in the
2nd row, 3rd column of A, thus
>> A(2,3)
ans =
5
Note MATLABs response when we ask for the entry in the 4th row, 1st column.
>> A(4,1)
??? Index exceeds matrix dimensions.
As expected, we get an error message. Since A is a 3-by-3 matrix, there is no 4th row and MATLAB realizes that.
Note that: The error messages that we get from MATLAB can be quite informative when trying to find out what
went wrong. In this case MATLAB told us exactly what the problem was.

EGYPTIAN ACADEMY OF
ENGINEERING & ADVANCED
TECHNOLOGY
(EAE&AT)

MATLAB / SIMULINK SUMMER


TRAINING COARSE

Page:8

We can extract submatrices using a similar notation as above. For example to obtain the submatrix that
consists of the first two rows and last two columns of A we type
A(1:2,2:3)

>>

ans =
2
4

3
5

We could even extract an entire row or column of a matrix, using the colon ( : ) as follows.

1- Columns: Suppose we want to get the 2nd column of A. We basically want the elements [A(1,2)
A(2,2) A(3,2)]. We type
>>

A(:,2)

ans =
2
4
7
2- Rows: we want to extract an entire row, say the 3rd one.
>> A(3,:)
ans =
6

The real power of MATLAB is the ease in which you can manipulate your vectors and matrices.
Example:
Defined now
1 2
A= 3 4
6 7

matrix B, and two vectors s and t as:


3
1 3 10
7
5 B= 9 5 25 S= [ 1 8 5 ] t= 0
8
0 14 2
11

[ ] [

Calculate the following:


(a) A-1
(b) A+B
(c) S-t'
(d) B*t
(e) A/B
(f) S.*S
>> B
-1 3
-9 5
0 14

= [
10
25
2]

B =
-1
-9

3
5

10
25

[]

EGYPTIAN ACADEMY OF
ENGINEERING & ADVANCED
TECHNOLOGY
(EAE&AT)

14

MATLAB / SIMULINK SUMMER


TRAINING COARSE

Page:9

>> s = [-1 8 5]
s =
-1

>> t = [7;0;11]
t =
7
0
11
(a) To subtract 1 from every entry in the matrix A we type
>> A-1
ans =
0
2
5

1
3
6

2
4
7

(b) It is just as easy to add (or subtract) two compatible matrices (i.e. matrices of the same size ; matrix
dimensions must agree). The same is true also for vectors.
>> A+B
ans =
0
-6
6

5
9
21

13
30
10

(c)
N.B., If we type:
>> s-t
The following error occurs,
??? Error using ==> minus
Matrix dimensions must agree.
>> s-t'
ans =
-8

-6

(d) For multiplication, Inner matrix dimensions must agree.


If we type:
>> B*s
The following error occurs,
??? Error using ==> mtimes

EGYPTIAN ACADEMY OF
ENGINEERING & ADVANCED
TECHNOLOGY
(EAE&AT)

Inner

matrix

dimensions

MATLAB / SIMULINK SUMMER


TRAINING COARSE

Page:10

must agree.

>> B*t
ans =
103
212
22
(e) Another important operation that MATLAB can perform with ease is matrix division.
>> A
A=
1
3
6

2
4
7

3
5
8

>> B
B=
-1 3 10
-9 5 25
0 14 2
>> A/B
ans =
0.7875 -0.1986
1.8222 -0.5358
3.3741 -1.0416

0.0450
0.0866
0.1490

To check your answer, try A/B=A*B-1


>> A*inv(B)
ans =
0.7875 -0.1986
1.8222 -0.5358
3.3741 -1.0416

0.0450
0.0866
0.1490

Check also, (A*B-1 )*B=A


>> ans*B
ans =
1.0000
3.0000
6.0000

2.0000
4.0000
7.0000

3.0000
5.0000
8.0000

EGYPTIAN ACADEMY OF
ENGINEERING & ADVANCED
TECHNOLOGY
(EAE&AT)

MATLAB / SIMULINK SUMMER


TRAINING COARSE

Page:11

(f) There are many times when we


want to perform an operation to every entry in a vector
or matrix. MATLAB will allow us to do this with element-wise operations.
For example, suppose you want to multiply each entry in the vector s with itself. In other words, suppose
you want to obtain the vector s = [s(1)*s(1), s(2)*s(2), s(3)*s(3)].
2

The command s*s will not work due to incompatibility. What is needed here is to tell MATLAB to perform the
multiplication element-wise. This is done with the symbols ".*". In fact, you can put a period in front of most
operators to tell MATLAB that you want the operation
to take place on each entry of the vector (or matrix).
>> s*s
??? Error using ==> mtimes
Inner matrix dimensions must agree.
>> s.*s
ans =
1

64

25

The symbol " .^ " can also be used since we are after all raising s to a power.
>> s.^2
ans =
1

64

25

Exercises:
1- Create a diary session called sec2_2 in which you should complete the following exercises.
Define

[ ] []

2
0
A=
7
7

9
4
5
8

0
1
5
7

0
4
, b=
1
4

1
6 , a=[ 3 2 4 5 ]
0
9

1. Calculate the following (when defined)


(a) A b (b) a + 4 (c) b a (d) a bT (e) A aT
2. Explain any differences between the answers that MATLAB gives when you type in A*A,
A^2 and A.^2.
3. What is the command that isolates the submatrix that consists of the 2nd to 3rd rows of the
matrix A?
4. Solve the linear system A x = b for x. Check your answer by multiplication.

(a)

E^3

[ ]

1 2
, Evaluate the following:
3 4
(b) E.^3 (c) E-1
(d) Eigen values of E

2- For the matrix E=

Lesson 2

EGYPTIAN ACADEMY OF
ENGINEERING & ADVANCED
TECHNOLOGY
(EAE&AT)

MATLAB / SIMULINK SUMMER


TRAINING COARSE

Page:12

Objectives:
MATLAB Basics
- Built-in functions.
- Arithmetic Operators.
- Relational Operators.
- Logical Operators.

Material:
Built-in functions:
1- Scalar Functions
Certain MATLAB functions are essentially used on scalars, but operate element-wise when
applied to a matrix (or vector). They are summarized in the table below.
sin trigonometric sine
cos trigonometric cosine
tan trigonometric tangent
asin trigonometric inverse sine (arcsine)
acos trigonometric inverse cosine (arccosine)
atan trigonometric inverse tangent (arctangent)
exp exponential
log natural logarithm
abs absolute value
sqrt square root
rem remainder
round round towards nearest integer
floor round towards negative infinity
ceil round towards positive infinity
Keep in mind that all of the above commands can be used on vectors with the operation taking place
element-wise.
The trigonometric functions take as input radians. Since MATLAB uses pi for the number
= 3.1415
>> sin(pi/2)
ans =
1
>> cos(pi/2)
ans =
6.1232e-017
The rem command gives the remainder of a division. So the remainder of 12
divided by 4 is zero
>> rem(12,4)
ans =
0

EGYPTIAN ACADEMY OF
ENGINEERING & ADVANCED
TECHNOLOGY
(EAE&AT)

MATLAB / SIMULINK SUMMER


TRAINING COARSE

Page:13

and the remainder of 12 divided by 5 is


>> rem(12,5)

2.

ans =
2
The floor, ceil and round commands are illustrated below.
>> floor(1.4)
ans =
1
>> ceil(1.4)
ans =
2
>> round(1.4)
ans =
1

For vectors and matrices:

x = [0:0.1:1]
x =
0 0.1000 0.2000 0.3000 0.4000 0.5000 0.6000
0.7000 0.8000 0.9000 1.0000
y = exp(x)
y =
1.0000 1.1052 1.2214 1.3499 1.4918 1.6487 1.8221
2.0138 2.2255 2.4596 2.7183
This is extremely useful when plotting data.
2- Vector Functions:
Other MATLAB functions operate essentially on vectors returning a scalar value. Some of these
functions are given in the table below.
max largest component
min smallest component
length length of a vector
sort sort in ascending order
sum sum of elements
prod product of elements
median median value
mean mean value
std standard deviation

N.B.,

mean: x =

1
1
x , std :s= n1
( x i x ) 2
n i=1 i
i=1

1
2

EGYPTIAN ACADEMY OF
ENGINEERING & ADVANCED
TECHNOLOGY
(EAE&AT)

Example:

MATLAB / SIMULINK SUMMER


TRAINING COARSE

Page:14

>> z = [0.9347,0.3835,0.5194,0.8310]
z =
0.9347

0.3835

0.5194

0.8310

0.5194

0.8310

0.9347

>> max(z)
ans =
0.9347
>> min(z)
ans =
0.3835
>> sort(z)
ans =
0.3835
>> sum(z)
ans =
2.6686
>> mean(z)
ans =
0.6672
>> std(z)
ans =
0.2587
The above (vector) commands can also be applied to a matrix (remember the vector functions act on matrices in
a column-by-column fashion).
Example:
Suppose we wanted to find the maximum element in the following matrix.
>> M = [
0.7012,0.2625,0.3282
0.9103,0.0475,0.6326
0.7622,0.7361,0.7564]
M =

EGYPTIAN ACADEMY OF
ENGINEERING & ADVANCED
TECHNOLOGY
(EAE&AT)

0.7012
0.9103
0.7622

0.2625
0.0475
0.7361

MATLAB / SIMULINK SUMMER


TRAINING COARSE

Page:15

0.3282
0.6326
0.7564

If we used the max command on M, we will get the row in which the maximum element lies
>> max(M)
ans =
0.9103
0.7361
0.7564
To isolate the largest element, we must use the max command on the above row vector. Taking
advantage of the fact that MATLAB assigns the variable name ans to the answer we obtained,
we can simply type
>> max(ans)
ans =
0.9103
The two steps above can be combined into one in the following.
>> max(max(M))
ans =
0.9103
For the mean & standard deviation functions, if x is a matrix, the results return a row
vector containing the mean or standard deviation of the elements of each column of X.
>> mean(M)
ans =
0.7912

0.3487

0.5724

0.3523

0.2204

>> std(M)
ans =
0.1075
3- Matrix Functions
Much of MATLABs power comes from its matrix functions.
eye identity matrix
zeros matrix of zeros
ones matrix of ones
diag extract diagonal of a matrix or create diagonal matrices
triu upper triangular part of a matrix
tril lower triangular part of a matrix
rand randomly generated matrix

EGYPTIAN ACADEMY OF
ENGINEERING & ADVANCED
TECHNOLOGY
(EAE&AT)

size
det
inv
eig
poly

MATLAB / SIMULINK SUMMER


TRAINING COARSE

Page:16

size of a matrix
determinant of a square matrix
inverse of a matrix
eigenvalues and eigenvectors
characteristic polynomial

>> eye(4,4)
ans =
1
0
0
0

0
1
0
0

0
0
1
0

0
0
0
1

>> zeros(2,3)
ans =
0
0

0
0

0
0

>> ones(2)
ans =
1
1

1
1

We can create a randomly generated matrix using the rand command. (The entries will be
uniformly distributed between 0 and 1.)
C =
0.8147
0.9058
0.1270
0.9134
0.6324

0.0975
0.2785
0.5469
0.9575
0.9649

0.1576
0.9706
0.9572
0.4854
0.8003

0.1419
0.4218
0.9157
0.7922
0.9595

The commands triu and tril, extract the upper and lower part of a matrix, respectively. Let
us try them on the matrix C defined above.
>> triu(C)
ans =
0.8147
0
0
0
0
>> tril(C)
ans =

0.0975
0.2785
0
0
0

0.1576
0.9706
0.9572
0
0

0.1419
0.4218
0.9157
0.7922
0

EGYPTIAN ACADEMY OF
ENGINEERING & ADVANCED
TECHNOLOGY
(EAE&AT)

0.8147
0.9058
0.1270
0.9134
0.6324

MATLAB / SIMULINK SUMMER


TRAINING COARSE

Page:17

0
0.2785
0.5469
0.9575
0.9649

0
0.9572
0.4854
0.8003

0
0
0
0.7922
0.9595

As mentioned earlier, the command diag has two uses;

The first use is to extract a diagonal of a matrix, e.g. the main diagonal.

>> D = [
0.9092 0.5045 0.9866
0.0606 0.5163 0.4940
0.9047,0.3190,0.2661];
>> diag(D)
ans =
0.9092
0.5163
0.2661
The second use is to create diagonal matrices. For example,
>> diag([0.9092;0.5163;0.2661])or >> diag(ans)
ans =
0.9092
0
0

0
0.5163
0

0
0
0.2661

Note: The Inverse and Determinants of 2x2 and 3x3 Matrices


The general way to calculate the inverse of any square matrix, is to append a unity matrix after the matrix (i.e. [A
| I]), and then do a row reduction until the matrix is of the form [I | B], and then B is the inverse of A. There is
also
a
general
formula
based
on
matrix
conjugates
and
the
determinant.
In the following, DET is the determinant of the matrices at the left-hand side.

The inverse of a 2x2 matrix:


| a11 a12 |-1
| a21 a22 |

with DET

a11a22-a12a21

| a22 -a12 |
1/DET * | -a21 a11 |

The inverse of a 3x3 matrix:


| a11 a12 a13 |-1
| a21 a22 a23 |
| a31 a32 a33 |
with DET

|
a33a22-a32a23 -(a33a12-a32a13)
a23a12-a22a13 |
1/DET * | -(a33a21-a31a23)
a33a11-a31a13 -(a23a11-a21a13) |
|
a32a21-a31a22 -(a32a11-a31a12)
a22a11-a21a12 |

a11(a33a22-a32a23)-a21(a33a12-a32a13)+a31(a23a12-a22a13)

EGYPTIAN ACADEMY OF
ENGINEERING & ADVANCED
TECHNOLOGY
(EAE&AT)

MATLAB / SIMULINK SUMMER


TRAINING COARSE

Page:18

Determining the Eigenvalues of a Matrix:


eigenvalues and eigenvectors make sense only for square matrices.
Given a square matrix A, the condition that characterizes an eigenvalue, , is the
existence of a nonzero vector x such that Ax = x; this equation can be rewritten as
follows:
Ax= x

Ax x=0
Ax Ix=0

( A I ) x=0

This final form of the equation makes it clear that x is the solution of a square,
homogeneous system. If nonzero solutions are desired, then the determinant of the
coefficient matrixwhich in this case is A Imust be zero; if not, then the system
possesses only the trivial solution x = 0. Since eigenvectors are, by definition, nonzero, in
order for x to be an eigenvector of a matrix A, must be chosen so that
det ( AI )=0

Roots of the previous equation are the eigenvalues of A.


Example 1: Determine the eigenvalues of the matrix

A=

1 2
3 4

First, form the matrix A I:

A I =

][ ][

1 2
0
1
2

=
3 4
0
3
4

EGYPTIAN ACADEMY OF
ENGINEERING & ADVANCED
TECHNOLOGY
(EAE&AT)

MATLAB / SIMULINK SUMMER


TRAINING COARSE

Page:19

a result which follows by simply


subtracting from each of the entries on
the main diagonal. Now, take the determinant of A I:

2 =( 1 ) (4 ) ( 3 ) (2 )
det ( AI )=det 1
3 4
2 +3 2

This is the characteristic polynomial of A, and the solutions of the characteristic equation,
det( A I) = 0, are the eigenvalues of A:
det ( AI )=0
2 +3 2=0

( +1 ) ( +2 ) =0
=1,2
In some texts, the characteristic polynomial of A is written det ( I A), rather than det (
A I). For matrices of even dimension, these polynomials are precisely the same, while
for square matrices of odd dimension, these polynomials are additive inverses. The
distinction is merely cosmetic, becaues the solutions of det ( I A) = 0 are precisely the
same as the solutions of det ( A I) = 0. Therefore, whether you write the characteristic
polynomial of A as det( I A) or as det( A I) will have no effect on the determination
of the eigenvalues or their corresponding eigenvectors.
Example 2:
Find the eigenvalues of the 3 by 3 checkerboard matrix

The determinant

EGYPTIAN ACADEMY OF
ENGINEERING & ADVANCED
TECHNOLOGY
(EAE&AT)

MATLAB / SIMULINK SUMMER


TRAINING COARSE

Page:20

The roots of the characteristic equation, 2( 3) = 0, are = 0 and = 3; these are


the eigenvalues of C.
Example 3:
A = [9,7,0;0,8,6;7,1,-6]
A =
9 7 0
0 8 6
7 1 -6
size(A)
ans =
3 3
det(A)
ans =
-192
Since the determinant is not zero, the matrix is invertible.
inv(A)
ans =
0.2812 -0.2187 -0.2187
-0.2187 0.2812 0.2812
0.2917 -0.2083 -0.3750
We can check our result by verifying that AA1 = I and A1A = I .
A*inv(A)
ans =
1.0000 0.0000 0.0000
0.0000 1.0000 0.0000
0.0000 0.0000 1.0000
inv(A)*A
ans =
1.0000 0.0000 0
0.0000 1.0000 0
0.0000 0 1.0000
eig(A)
ans =
12.6462
3.1594
-4.8055
Polynomial with specified roots:

EGYPTIAN ACADEMY OF
ENGINEERING & ADVANCED
TECHNOLOGY
(EAE&AT)

MATLAB / SIMULINK SUMMER


TRAINING COARSE

Page:21

The algorithms employed for poly and


roots illustrate an interesting aspect of the modern
approach to eigenvalue computation. poly(A) generates the characteristic polynomial of A, and roots(poly(A))
finds the roots of that polynomial, which are the eigenvalues of A.
If A is an n-by-n matrix, poly(A) produces the coefficients c(1) through c(n+1), with c(1) = 1, in
det ( 1 ) =c 1 n+ +c n +c n+1
MATLAB displays polynomials as row vectors containing the coefficients ordered by descending powers. The
characteristic equation of the matrix
A =
1
4
7

2
5
8

3
6
0

is returned in a row vector by poly:


p = poly(A)
p =
1

-6

-72

-27

The roots of this polynomial (eigenvalues of matrix A) are returned in a column vector by roots:
r = roots(p)
r =
12.1229
-5.7345
-0.38

Arithmetic Operators:
1. Scalar Arithmetic Operators.
+ Addition
a+b
- Subtraction
ab
* Multiplication
a*b
/ Division
a/b
^ Exponential
a^b
Here is an example how to use some of the operators:
>> m1'*v1+1-[1;2;3;4]
2. Matrix Element-by-Element Arithmetic Operators (Dotted operators):
+
.*
./
.^

Addition
Subtraction
Multiplication
Division
Exponential

a+b
ab
a .* b
a ./ b
a .^ b

An example how to use them:

EGYPTIAN ACADEMY OF
ENGINEERING & ADVANCED
TECHNOLOGY
(EAE&AT)

MATLAB / SIMULINK SUMMER


TRAINING COARSE

Page:22

>>

v1.*[1;2;3]+[4;5;6].^3

Relational Operators:
Relational operators are used in comparing two values.
Operator
<
<=
>
>=
~=

Meaning
Less than
Less than or equal to
Greater than
Greater than or equal to
Not equal to

The result of applying a relational operator is a logical value, i.e. the result is either true
or false. In Matlab any nonzero value, including a non-empty string, is equivalent to true.
Only zero is equivalent to false.

Note: The <=, >=, and ~= operators have = as the second character. =<, => and
=~ are not valid operators.
The result of a relational operation is a true or false value.

Examples:
>> a = 2; b = 4;
>> aIsSmaller = a < b
aIsSmaller =
1
>> bIsSmaller = b < a
bIsSmaller =
0
Relational operations can also be performed on matrices of the same shape, e.g.,
>> x = 1:5; y = 5:-1:1;
>> z = x>y
z=
00011

Logical Operators:
Logical operators are used to combine
change a logical value with not.
Operator
&
|
~

Examples:
>> a = 2; b = 4;
>> aIsSmaller = a < b;
>> bIsSmaller = b < a;
>> bothTrue = aIsSmaller & bIsSmaller
bothTrue =
0
>> eitherTrue = aIsSmaller | bIsSmaller
eitherTrue =
1
>> ~eitherTrue
ans =

logical expressions (with and or or), or to


Meaning
And
Or
not

EGYPTIAN ACADEMY OF
ENGINEERING & ADVANCED
TECHNOLOGY
(EAE&AT)

MATLAB / SIMULINK SUMMER


TRAINING COARSE

Page:23

Logical and Relational Operators


Before moving on, check whether you now understand the following relations:

>> a = randperm(10);
>> b = 1:10;
>> b - (a <= 7)
0 otherwise
>> (a >= 2) & (a < 4)
>> ~(b > 4)
>> (a == b) | b == 3
is equal to 3
>> any(a > 5)
5
>> any(b < 5 & a > 8)
>>
>> all(b > 2)

% random permutation
% subtracts from b a 0-1 vector, taking 1 for a <= 7 and
% returns ones at positions where 2 <= a < 4
% returns ones at positions where b <= 4
% returns ones at positions where a is equal to b or b
% returns 1 when ANY of the a elements are larger than
% returns 1 when there in the evaluated expression
% (b < 5 & a > 8) appears at least one 1
% returns 1 when ALL b elements are larger than 2

Example: You can extract all elements from the vector or the matrix satisfying a given
condition, e.g. equal to 1 or larger than 5, by using logical addressing. The same result
can be obtained via the command find, which return the positions (indices) of such
elements. For instance:
>> x = [1 1 3 4 1];
i = (x == 1)
i=
1

>> y = x(i)
y=
1

>> j = find(x == 1)
j=
1

>> z = x(j)
z=
1

Another example is:


>> x = -1:0.05:1;
y = sin(x) .* sin(3*pi*x);
plot (x,y, '-'); hold on
k = find (y <= -0.1)

% j holds indices of those elements satisfying x == 1

EGYPTIAN ACADEMY OF
ENGINEERING & ADVANCED
TECHNOLOGY
(EAE&AT)

MATLAB / SIMULINK SUMMER


TRAINING COARSE

Page:24

k=
9

10

11

12

13

29

>> plot (x(k), y(k), 'ro');

>> r = find (x > 0.5 & y > 0)

30

31

32

33

EGYPTIAN ACADEMY OF
ENGINEERING & ADVANCED
TECHNOLOGY
(EAE&AT)

MATLAB / SIMULINK SUMMER


TRAINING COARSE

Page:25

r=
35

36

37

38

39

40

41

>> plot (x(r), y(r), 'r*');

find operates in a similar way on matrices:


>> A = [1 3 -3 -5; -1 2 -1 0; 3 -7 2 7];
k = find (A >= 2.5)
k=
3
4
12
>> A(k)
ans =
3
3
7
In this way, finds reshapes first the matrix A into a column vector, i.e. it operates on A(:),
i.e. all columns are concatenated one after another. Therefore, k is a list of indices of
elements larger than or equal to 2:5 and A(k) gives the values of the selected elements.
Also the row and column indices can be returned, as shown below:
>> [I,J] = find (A >= 2.5)

EGYPTIAN ACADEMY OF
ENGINEERING & ADVANCED
TECHNOLOGY
(EAE&AT)

MATLAB / SIMULINK SUMMER


TRAINING COARSE

Page:26

I=
3
1
3
J=
1
2
4
>> [A(I(1),J(1)), A(I(2),J(2)), A(I(3),J(3))]

% lists the values

ans =
3

Summary:
Relational operators involve comparison of two values.
The result of a relational operation is a logical (True/False) value.

Exercises:
Exercise with logical and relational operators:
1- Let x = [1 5 2 8 9 0 1] and y = [5 2 2 6 0 0 2]. Execute and explain the results of
the following commands:
x>y
y<x
x == y
x <= y
y >= x
x|y
x & (~y)
(x > y) | (y < x)
(x > y) & (y < x)
2- Let x = 1 : 10 and y = [3 5 6 1 8 2 9 4 0 7]. The exercises here show the techniques
of logical-indexing.
Execute and interpret the results of the following commands:
(x > 3) & (x < 8)
x (x > 5)
y (x <= 4)
x ((x < 2) | (x >= 8))
y ((x < 2) | (x >= 8))
x (y < 0)
3- Let x = [3 16 9 12 -1 0 -12 9 6 1]. Provide the command(s) that will:
Set the positive values of x to zero;

EGYPTIAN ACADEMY OF
ENGINEERING & ADVANCED
TECHNOLOGY
(EAE&AT)

MATLAB / SIMULINK SUMMER


TRAINING COARSE

Page:27

Set values
that are multiples of 3 to 3 (make use of
rem);
Multiply the even values of x by 5;
Extract the values of x that are greater than 10 into a vector called y;
Set the values in x that are less than the mean to 0;
Set the values in x that are above the mean to their difference from the
mean.

Lesson 3
Objectives:
-

Solving algebraic equations (polynomials):


1- Single equation.
2- System of equations.
3- Curve Fitting.
Solving differential equations:
4- First order differential equations.
5- Second and higher order differential equations.
6- System of differential equations.

Material:

EGYPTIAN ACADEMY OF
ENGINEERING & ADVANCED
TECHNOLOGY
(EAE&AT)

Solving equations using

MATLAB / SIMULINK SUMMER


TRAINING COARSE

Page:28

MATLAB:

Polynomials
In Matlab polynomial is represented by row vector of its coefficients in descending
order.
Example: P= x4 12x3 + 25x +16 is entered as
>> P = [1 -12 0 25 16]
P=
1 -12
0
>> roots(P)

25

16

ans =
11.8111
1.8218
-0.8165 + 0.2774i
-0.8165 - 0.2774i
Inversely, to get the equation of the roots:
>> poly(ans)
ans =
1.0000 -12.0000 -0.0000 25.0000 16.0000
To calculate P value when x=2:
>> v=polyval(P,2)
v=
-14
You can solve equations involving variables with solve or fzero.
For example, to find the solutions of the quadratic equation x2 2x 4 = 0,
Type
>> solve('x^2-2*x-4=0')
ans =
1 - 5^(1/2)
5^(1/2) + 1

Note that the equation to be solved is specified as a string; that is, it is surrounded by single quotes. The answer
consists of the exact (symbolic) solutions 1 5. To get numerical solutions, type double (ans), or vpa (ans) to
display more digits.

EGYPTIAN ACADEMY OF
ENGINEERING & ADVANCED
TECHNOLOGY
(EAE&AT)

MATLAB / SIMULINK SUMMER


TRAINING COARSE

Page:29

>> double(ans)
ans =
-1.2361
3.2361
Or
>> vpa(ans)
ans =
-1.2360679774997896964091736687313
3.2360679774997896964091736687313

Linear system of equations


Consider the set of equations

Example:
x1+3x3=5, 5x2+6x3=-2,

7x1+8x2=3

Get x1, x2, x3

Solution:

[ ][ ] [ ]
1 0 3 x1
5
0 5 6 x 2 = 2
7 8 0 x3
3

>> A = [1 0 3;0 5 6;7 8 0]; b = [5;-2;3]; x = inv(A)*b


x=
2.1765
-1.5294
0.9412

The command solve can solve higher-degree polynomial equations, as well as many other types of
equations. It can also solve equations involving more than one variable. If there are fewer equations than
variables, you should specify (as strings) which variable(s) to solve for. For example, type solve ('2*x log(y) = 1', 'y') to solve 2x log y = 1 for y in terms of x.

>> solve ('2*x - log(y) = 1', 'y')


ans =
exp(2*x - 1)

You can specify more than one equation as well. For example,

>> [x,y]=solve('x^2-y=2','y-2*x=5')
x=

EGYPTIAN ACADEMY OF
ENGINEERING & ADVANCED
TECHNOLOGY
(EAE&AT)

MATLAB / SIMULINK SUMMER


TRAINING COARSE

Page:30

2*2^(1/2) + 1
1 - 2*2^(1/2)

y=
4*2^(1/2) + 7
7 - 4*2^(1/2)
This system of equations has two solutions. MATLAB reports the solution by giving the two x values and the
two y values for those solutions. Thus the first solution consists of the first value of x together with the first value
of y. You can extract these values by typing x (1) and y (1):
>> x(1)
ans =
2*2^(1/2) + 1
>> y(1)
ans =
4*2^(1/2) + 7
The second solution can be extracted with x(2) and y(2). Note that in the preceding solve command, we assigned
the output to the vector [x, y]. If you use solve on a system of equations without assigning the output to a vector,
then MATLAB does not automatically display the values of the solution:
>> solve('x^2-y=2','y-2*x=5')
ans =
x: [2x1 sym]
y: [2x1 sym]
To see the vectors of x and y values of the solution, type sol.x and sol.y. To see the individual values, type
ans.x(1), ans.y(1), etc.
>> ans.x(1)
ans =
2*2^(1/2) + 1
Some equations cannot be solved symbolically, and in these cases solve tries to find a numerical answer. For
example,
>> solve('sin(x) = 2 x')
ans =
1.1060601577062719106167372970301
Sometimes there is more than one solution, and you may not get what you

EGYPTIAN ACADEMY OF
ENGINEERING & ADVANCED
TECHNOLOGY
(EAE&AT)

MATLAB / SIMULINK SUMMER


TRAINING COARSE

Page:31

expected. For example,


>> solve('exp(-x) = sin(x)')
ans =
-2.0127756629315111633360706990971
+2.7030745115909622139316148044265*i

Suppose you want to multiply two polynomials together. Their product is found by taking the convolution
of their coefficients. MATLABs command conv will do this for you. For example, if s(x) = x + 2 and t(x)
= x2 + 4x + 8 then z(x) = s(x) t(x) = x3 + 6x2 + 16x + 16.

In MATLAB, we type
>> s = [1 2];
>> t = [1 4 8];
>> z = conv(s,t)
z =
1

16

16

Dividing two polynomials is just as easy. The deconv function will return the remainder as well as the
result. Lets divide z by t and see if we get s.
>> [s,r] = deconv(z,t)
s =
1

r =
0

(residue)

As you can see, we get (as expected) the polynomial/vector s from before. If s did not divide z exactly, the
remainder vector r, would have been something other than zero.

MATLAB can obtain derivatives of polynomials very easily. The command polyder takes as input the
coefficient vector of a polynomial and returns the vector of coefficients for its derivative.
For example, with p(x) = x 3x + 5
2

>> p=[1 -3 5]
p =
1

-3

>> polyder(p)
ans =
1- -3
>> a = [3 6 9];
b = [1 2 0];

EGYPTIAN ACADEMY OF
ENGINEERING & ADVANCED
TECHNOLOGY
(EAE&AT)

MATLAB / SIMULINK SUMMER


TRAINING COARSE

Page:32

k = polyder(a,b)
k =
12
36
42
18
This result represents the polynomial:

12 x 3 +36 x 2+42 x +18

Also, to illustrate how to take derivatives using Symbolic Math Toolbox software, first create a symbolic
expression:
>> f= sin(5*x)
f=
sin(5*x)
>> diff(f)
ans =
5*cos(5*x)
As another example, let
>> g = exp(x)*cos(x)
g=
exp(x)*cos(x)
>> diff(g)
ans =
exp(x)*cos(x) - exp(x)*sin(x)
To take the second derivative of g, enter
>> diff (g,2)
ans =
(-2)*exp(x)*sin(x)
You can get the same result by taking the derivative twice:
>> diff(diff(g))
ans =
(-2)*exp(x)*sin(x)

MATLAB can integrate polynomials very easily. The command polyint(p,k) returns a
polynomial representing the integral of polynomial p, using a scalar constant of
integration k.

EGYPTIAN ACADEMY OF
ENGINEERING & ADVANCED
TECHNOLOGY
(EAE&AT)

Curve Fitting:
p = polyfit(x,y,n) finds
polynomial
p(x)
of
data, p(x(i)) to y(i), in a
result p is a row vector
the
polynomial
descending powers:

Input voltage (V)


2.87
2.86
2.85
2.84
2.83
2.82
2.81
2.80
2.79
2.78
2.77
2.76
2.75
2.74

MATLAB / SIMULINK SUMMER


TRAINING COARSE

Page:33

Output voltage (V)


2.6
2.8
3.0
4.4
5.0
5.2
5.4
5.6
5.7
5.8
5.9
6.1
6.3
6.4

the coefficients of a
degree n that fits the
least squares sense. The
of length n+1 containing
coefficients
in

p ( x )= p 1 x n+ p 2 x n1 ++ pn x+ p n+1
Example:
For the following practical results of the control circuit, find the relation between the input and the output:

Program of curve fitting:


clear all;close all;clc
x=[2.87 2.86 2.85 2.84 2.83 2.82 2.81 2.80 2.79 2.78 2.77 2.76 2.75 2.74];
y=[2.6 2.8 3 4.4 5 5.2 5.4 5.6 5.7 5.8 5.9 6.1 6.3 6.4];
p=polyfit(x,y,4)
k=polyval(p,x);

EGYPTIAN ACADEMY OF
ENGINEERING & ADVANCED
TECHNOLOGY
(EAE&AT)

MATLAB / SIMULINK SUMMER


TRAINING COARSE

Page:34

plot(x,k);
hold on
plot(x,y,'red')
grid on
title('Relation between Vin & Vout')
xlabel('Input voltage (V)')
ylabel('Output voltage (V)')
legend('Actual measured curve','4th degree aprroximated relationship')

By omitting the semicolon (;) of the polyfit line, the output relationship will be displayed in the
MATLAB prompt, which can be expressed as follows:
p ( x )=1.0e+006(0.0736 x 40.8279 x 3 +3.4914 x 2+6.5424 x + 4.5966)
The plotted curves are as follows:

Solving Differential equations:


First Order Equations
Though MATLAB is primarily a numerics package, it can certainly solve straightforward
differential equations symbolically.1 Suppose, for example, that we want to solve the first
order differential equation
y(x) = xy.
We can use MATLABs built-in dsolve().
>> y = dsolve('Dy = y*x','x')
y=

EGYPTIAN ACADEMY OF
ENGINEERING & ADVANCED
TECHNOLOGY
(EAE&AT)

MATLAB / SIMULINK SUMMER


TRAINING COARSE

Page:35

C2*exp(x^2/2)
Notice in particular that MATLAB uses capital D to indicate the derivative and requires
that the entire equation appear in single quotes. MATLAB takes t to be the independent
variable by default, so here x must be explicitly specified as the independent variable.
Alternatively, if you are going to use the same equation a number of times, you might
choose to define it as a variable, say, eqn1.
>> eqn1 = 'Dy = y*x'
eqn1 =
Dy = y*x
>> y = dsolve(eqn1,'x')
y=
C5*exp(x^2/2)
To solve an initial value problem, say, equation (1.1) with y(1) = 1, use
>> y = dsolve(eqn1,'y(1)=1','x')
y=
exp(x^2/2)/exp(1)^(1/2)
Or
>> inits = 'y(1)=1';
>> y = dsolve(eqn1,inits,'x')
y=
exp(x^2/2)/exp(1)^(1/2)

Second and Higher Order Equations:

Suppose we want to solve and plot the solution to the second order equation
y"(x) + 8y(x) + 2y(x) = cos(x); y(0) = 0, y'(0) = 1
The following (more or less self-explanatory) MATLAB code suffices:
>> eqn2 = 'D2y + 8*Dy + 2*y = cos(x)';
>> inits2 = 'y(0)=0, Dy(0)=1';
>> y=dsolve(eqn2,inits2,'x')
y=
(14^(1/2)*exp(4*x - 14^(1/2)*x)*exp(x*(14^(1/2) - 4))*(sin(x) - cos(x)*(14^(1/2) - 4)))/
(28*((14^(1/2) - 4)^2 + 1)) - (98*14^(1/2) + 378)/(exp(x*(14^(1/2) + 4))*(868*14^(1/2)

EGYPTIAN ACADEMY OF
ENGINEERING & ADVANCED
TECHNOLOGY
(EAE&AT)

MATLAB / SIMULINK SUMMER


TRAINING COARSE

Page:36

+ 3136)) - (14^(1/2)*exp(4*x +
14^(1/2)*x)*(sin(x) + cos(x)*(14^(1/2) +
4)))/(28*exp(x*(14^(1/2) + 4))*((14^(1/2) + 4)^2 + 1)) - (exp(x*(14^(1/2) 4))*(98*14^(1/2) - 378))/(868*14^(1/2) - 3136)
System of differential equations:
Suppose we want to solve and plot solutions to the system of three ordinary differential
equations
x'(t) =x(t) + 2y(t) z(t)
y'(t) =x(t) + z(t)
z'(t) =4x(t) 4y(t) + 5z(t)
First, to find a general solution, we proceed as previously mentioned, except with each
equation now braced in its own pair of (single) quotation marks:
>> [x,y,z]=dsolve('Dx=x+2*y-z','Dy=x+z','Dz=4*x-4*y+5*z')
x=
- (C11*exp(t))/2 - (C12*exp(2*t))/2 - (C13*exp(3*t))/4

y=
(C11*exp(t))/2 + (C12*exp(2*t))/4 + (C13*exp(3*t))/4

z=
C11*exp(t) + C12*exp(2*t) + C13*exp(3*t)
To solve an initial value problem, we simply define a set of initial values and add them at
the end of our dsolve() command. Suppose we have x(0) = 1, y(0) = 2, and z(0) = 3. We
have, then,
>> inits='x(0)=1,y(0)=2,z(0)=3';
>> [x,y,z]=dsolve('Dx=x+2*y-z','Dy=x+z','Dz=4*x-4*y+5*z',inits)
x=
6*exp(2*t) - (5*exp(3*t))/2 - (5*exp(t))/2

y=
(5*exp(3*t))/2 - 3*exp(2*t) + (5*exp(t))/2

z=
10*exp(3*t) - 12*exp(2*t) + 5*exp(t)

Laplace Transformation:

EGYPTIAN ACADEMY OF
ENGINEERING & ADVANCED
TECHNOLOGY
(EAE&AT)

MATLAB / SIMULINK SUMMER


TRAINING COARSE

Page:37

One of the most useful tools in


mathematics is the Laplace transform.
MATLAB has built-in routines for computing both Laplace transforms and inverse Laplace
transforms.
For example, to compute the Laplace transform of f(t) = t , type simply
>> syms t;
>> laplace (t^2)
2

ans =
2/s^3
In order to invert, say, F(s) = 1/1+s , type
>> syms s;
>> ilaplace (1/(s+1))
ans =
1/exp(t)
Exercise:
Find the roots of the following polynomials:
p(x) = x 3x + 5
q(x) = x + 7x x
Evaluate p(x), q(x) for x=7
2
4

Sol.
The roots of p(x) = x 3x + 5 is represented by the vector p = [1, -3, 5] and the polynomial q(x) = x4 +
7x2 x is represented by q = [1, 0, 7, -1, 0] .
MATLAB can interpret any vector of length n + 1 as an nth order polynomial. Thus, if your
polynomial is missing any coefficients, you must enter zeros in the appropriate place(s) in the
vector, as done above.
>> p = [1, -3, 5] ;
>> roots(p)
2

ans =
1.5000 + 1.6583i
1.5000 - 1.6583i
>> polyval(p,-1)
ans =
9
>> q = [1, 0, 7, -1, 0];
>> roots(q)
ans =
0
-0.0712 + 2.6486i

EGYPTIAN ACADEMY OF
ENGINEERING & ADVANCED
TECHNOLOGY
(EAE&AT)

MATLAB / SIMULINK SUMMER


TRAINING COARSE

Page:38

-0.0712 - 2.6486i
0.1424
>> polyval(q,-1)
ans =
9
Example :
2 1 2
1
1 0 9 X = 0
11 2 4
4

) ()

Exercise :
Solve u' ( x )=v ( x ) + x
Where u(0)=1, v(0)=2.
Answer: u(x)=1.5ex-0.5e-x
Example :
Evaluate x , y, z where
2x+y+2z=-1
-x+9z=0
11x+2y+4z=4

v ' ( x ) =u ( x )1

,
,

v(x)=-x+1.5ex+0.5e-x

EGYPTIAN ACADEMY OF
ENGINEERING & ADVANCED
TECHNOLOGY
(EAE&AT)

Example:

MATLAB / SIMULINK SUMMER


TRAINING COARSE

Page:39

EGYPTIAN ACADEMY OF
ENGINEERING & ADVANCED
TECHNOLOGY
(EAE&AT)

Exercises:

1- Evaluate the
when x=2.
2- Solve
the
2
15x -2x+9
3- Evaluate
Z
multiply
of
polynomials:
(a)
(b)y=s2

Input Voltage (V)


2.87
2.86
2.85
2.84
2.83
2.82
2.81
2.80
2.79
2.78
2.77
2.76
2.75
2.74

MATLAB / SIMULINK SUMMER


TRAINING COARSE

Page:40

Speed (r.p.m)
117.5
255.0
286.0
330.0
341.0
365.0
382.0
418.0
450.0
515.0
608.0
698.0
706.0
745.0

polynomial y=x4+1
equation y=x4+3x3polynomial is the
the
following
x=s+2
+4s+8

then check your answer


by dividing Z by y to get
x.
4- For
the
following
experimental
results, find the
best
relationship
between the I/P & O/P. Plot the curves to compare between the actual results with
the calculated approximated results.

EGYPTIAN ACADEMY OF
ENGINEERING & ADVANCED
TECHNOLOGY
(EAE&AT)

MATLAB / SIMULINK SUMMER


TRAINING COARSE

Page:41

Lesson 4
Objectives:
-

Programming using MATLAB (M File).


Conditional Execution.
Loops.

Material:

All functions of the MATLAB prompt can be used in the m-file.


M-Files:
For simple problems, it efficient to use the command window, but for complicated problems, the simple
editing tools provided by the Command Window and its history mechanism are insufficient. A much better
approach is to create an M-file.
Creating a New File in the Editor
To create a new text file in the Editor, either click the New M-file button on the MATLAB desktop
toolbar, or select File > New > M-File from the MATLAB desktop as shown in the figure below. The Editor
opens, if it is not already open, with an untitled file in the MATLAB current directory, in which you can create an
M-file or another type of text file.

Our First M File Program


Traditional programming books begin by writing the words Hello World to the screen, or a variation on
that statement. This time-honored tradition is carried on here.

EGYPTIAN ACADEMY OF
ENGINEERING & ADVANCED
TECHNOLOGY
(EAE&AT)

MATLAB / SIMULINK SUMMER


TRAINING COARSE

Page:42

Create new m-file as previously illustrated, we now show how to construct a script M-file to write our hello word
program in the editor as follows:

1- clc
2- disp(Hello word!)
In line No.1, we find clc to tell the compiler to clear the command window.
In line No. 2, disp is the command which is responsible for writing the words between brackets in the
command windows. Press F5 button to save and run the program, the output will be displayed in the command
window as shown in the next figure:

Adding Comments
It is worthwhile to include comments in a lengthy script M-file. These comments might explain what is
being done in the calculation, or they might interpret the results of the calculation. Any line in a script M-file that
begins with a percent sign % is treated as a comment and is not executed by MATLAB.

Data Inputs & Outputs:


Data Input:
1- Input parameters to functions are preferred, through the MATLAB prompt.
2- Reading data from a text data file (load & save):
MATLAB has some simple facilities for loading and saving data.
- For instance, suppose x = [1 2 3 4 5] and y = [4 13 26 43 64]. These variables can
be saved to a file called xydata.dat by:
>> x = [1 2 3 4 5] ;
>> y = [4 13 26 43 64];
>> save xydata.dat x y ascii
-

Thus, new file "xydata.dat" file is created in the MATLAB working directory. This
stores the data x and y into a file containing ascii data (as opposed to binary data).

EGYPTIAN ACADEMY OF
ENGINEERING & ADVANCED
TECHNOLOGY
(EAE&AT)

MATLAB / SIMULINK SUMMER


TRAINING COARSE

Page:43

- You can check the data is there by typing:


>> type xydata.dat
1.0000000e+000
5.0000000e+000
4.0000000e+000
6.4000000e+001

2.0000000e+000

3.0000000e+000

4.0000000e+000

1.3000000e+001

2.6000000e+001

4.3000000e+001

This generates a file with two rows of five numbers, being the data for x then that for y.
To load data you type
>> load xydata.dat
this will generate a 2D matrix called xydata, appears in the workspace pane, as shown in
the below figure. The first row will have the data which was in x, the second row will have
the data which was in y.

EGYPTIAN ACADEMY OF
ENGINEERING & ADVANCED
TECHNOLOGY
(EAE&AT)

MATLAB / SIMULINK SUMMER


TRAINING COARSE

Page:44

Generated xydata matrix

You can then access elements from the matrix variable xydata. Not xydata does not
known about the variables x and y; it is just a matrix with data.
>> xydata
xydata =
1
4

2
13

3
4
5
26 43 64

Example 2 - Reading data from a text file "readings.dat"


In your working directory, create the following text file: readings.dat, consisting of time
(say) and data columns:
Data

Data
1

Data
2

10

11

12

13

14

2.2

Time

Now, we can create the readings.dat file in the same working directory containing
this data using MATLAB as follows:

>> Time_data1_data2=[10 5 7 ; 11 6 3; 12 8 7; 13 1 0; 14 2.2 -9]


Time_data1_data2 =
10.0000
11.0000
12.0000

5.0000
6.0000
8.0000

7.0000
3.0000
7.0000

EGYPTIAN ACADEMY OF
ENGINEERING & ADVANCED
TECHNOLOGY
(EAE&AT)

13.0000
14.0000

MATLAB / SIMULINK SUMMER


TRAINING COARSE

Page:45

1.0000
0
2.2000 -9.0000

>> save readings.dat Time_data1_data2 ascii


(Note, the *.dat file you should contain ascii data.)
To display the *.dat file contents on the MATLAB prompt:
>> type readings.dat
1.0000000e+001
1.1000000e+001
1.2000000e+001
1.3000000e+001
1.4000000e+001

5.0000000e+000
6.0000000e+000
8.0000000e+000
1.0000000e+000
2.2000000e+000

7.0000000e+000
3.0000000e+000
7.0000000e+000
0.0000000e+000
-9.0000000e+000

You can read a text file in to Matlab using


>> load readings.dat
The variable "readings" appear in the workspace, double click on it to open its contents.

(If the file is in a different directory, include the entire path)


You will now have an array called readings. Break it up into column arrays (vectors):
>> time=readings(:,1)
time =
10
11
12
13
14
>> data1=readings(:,2)
data1 =

EGYPTIAN ACADEMY OF
ENGINEERING & ADVANCED
TECHNOLOGY
(EAE&AT)

MATLAB / SIMULINK SUMMER


TRAINING COARSE

Page:46

5.0000
6.0000
8.0000
1.0000
2.2000
And so on.

Data Outputs:

1. disp function for simple output


disp Simple to use. Provides limited control over appearance of output.
The format function controls the precision of disp output.
>> format short
>> disp (pi)
3.1416
>> format long
>> disp (pi)
3.141592653589793
Alternatively, a second parameter can be used to control the precision of the output of
num2str
>> disp(['pi =',num2str(pi,2)])
pi =3.1
>> disp(['pi =',num2str(pi,4)])
pi =3.142
>> disp(['pi =',num2str(pi,8)])
pi =3.1415927
2. fprintf function for formatted output.
fprintf Slightly more complicated than disp. Provides total control over appearance of
output.
>> x = 3;
>> fprintf(Square root of %g is %8.6f\n,x,sqrt(x));
The square root of 3 is 1.732051
The formats %g, %f, illustrates floating point numbers.

Conditional Execution
1- If statement
There are times when you would like your algorithm/code to make a decision, and the if statement is the way
to do it.

EGYPTIAN ACADEMY OF
ENGINEERING & ADVANCED
TECHNOLOGY
(EAE&AT)

The general syntax in MATLAB is as follows:


if relation
statement(s)
elseif relation % if applicable
statement(s) % if applicable
else % if applicable
statement(s) % if applicable
end

Example 1:
>> sum=6
sum =
6
>> if sum>=0 disp(sum)
elseif sum==-5 disp(sum/2)
else
disp(['Calculate sum'])
end
6
>> sum=-5
sum =
-5
>> if sum>=0 disp(sum)
elseif sum==-5 disp(sum/2)
else

MATLAB / SIMULINK SUMMER


TRAINING COARSE

Page:47

EGYPTIAN ACADEMY OF
ENGINEERING & ADVANCED
TECHNOLOGY
(EAE&AT)

MATLAB / SIMULINK SUMMER


TRAINING COARSE

Page:48

disp(['Calculate sum'])
end
-2.500000000000000
>> sum=-2
sum =
-2
>> if sum>=0 disp(sum)
elseif sum==-5 disp(sum/2)
else
disp(['Calculate sum'])
end
Calculate sum
Example 2:
>> x=-1;
>> if x<0
disp('x is negative, sqrt is imaginary');
else
r=sqrt(x)
end
x is negative, sqrt is imaginary
Example 3:
>> colour='blue'
colour =
blue
if strcmp(colour,'red')==1 disp('colour is red')
elseif strcmp(colour,'blue')==1 disp('colour is blue')
elseif strcmp(colour,'green')==1 disp('colour is green')
else disp('colour is not red, blue, green')
end
colour is blue

2- Switch case:
The switch command executes particular statements based on the value
of a variable or an expression.
Its general form is
>> switch <variable or expression>
case <Value 1>,
<statement group 1>
case f<Value 2a>, <Value 2b>, <Value 2c>, ..., <Value 2m>g,

EGYPTIAN ACADEMY OF
ENGINEERING & ADVANCED
TECHNOLOGY
(EAE&AT)

MATLAB / SIMULINK SUMMER


TRAINING COARSE

Page:49

<statement group 2>


...
case <value n>,
<statement group r>
otherwise,
<statement group r+1>
end
>> switch color
case 'red'
disp('color is
case 'blue'
disp('color is
case 'green'
disp('color is
otherwise
disp('color is
end

red')
blue')
green')
not red, blue, green')

(Note; switch not Switch, disp not Disp, case not Case, otherwise not Otherwise, end not
End).

Loops
1- For loop:
The general form of the for loop is
>> for <variable> = <expression>
<statement>
...
<statement>
End
Examples:
1- To calculate the expression of x for n times.

>> for i = 1:n


x(i) = i * sin( i^2 *pi/n );
end
2- To create a matrix H(i,j) of a specific elements:
>> for i = 1:n
for j = 1:n
H(i,j) = (i+j)/2;

EGYPTIAN ACADEMY OF
ENGINEERING & ADVANCED
TECHNOLOGY
(EAE&AT)

MATLAB / SIMULINK SUMMER


TRAINING COARSE

Page:50

end
end
3- To generate a random matrix, get the number of elements
exceed 0.5:

which their values

nr_elements=0;
m=7;
n=7;
f=rand(m,n);
for i = 1:m
for j = 1:n
if f(i,j)>0.5
nr_elements = nr_elements + 1;
end
end
end
f, nr_elements

We can also convert a non-logical variable to a logical one by using the MATLAB
command logical. To explain logical arrays more clearly, we take a speci_c and very
simple example.

>> v = [0:.25:1];
>> c = (v >= .5);
so that v = [0 .25 .5 .75 1.0] and c = [0 0 1 1 1] where "0" denotes false and "1" denotes
true.
The result of
>> v(c);
is [.5 .75 1.0]. That is, c is a logical vector and v(c) deletes the elements of v which are
"false".
On the other hand
>> iv = find(v < .5);
returns iv = [1 2]
>>for ii=1:5,
for jj=1:3,
A(ii,jj)=(ii+jj)/3;
end
end

Here is an example showing if, else, and elseif.


>> for m = 1:k
for n = 1:k
if m == n
a(m,n) = 2;
elseif abs(m-n) == 2
a(m,n) = 1;
else
a(m,n) = 0;
end

% ends jj loop
% ends ii loop

EGYPTIAN ACADEMY OF
ENGINEERING & ADVANCED
TECHNOLOGY
(EAE&AT)

MATLAB / SIMULINK SUMMER


TRAINING COARSE

Page:51

end
end
For k=5 you get the matrix
a =
2
0
1
0
0

0
2
0
1
0

1
0
2
0
1

0
1
0
2
0

0
0
1
0
2

2- While loop:
>> while <logical expression>
<statement>
...
<statement>
End
where the statements are executed repeatedly as long as the <logical expression> is
true.
For example,
A simple for loop would be structured as,
>>for Index=[1 2 3 4 5],
disp(Index)
end
Similar output can be obtained from a while loop:
>> Index=1;
>> while Index <= 5,
disp(Index)
Index=Index+1;
end

EGYPTIAN ACADEMY OF
ENGINEERING & ADVANCED
TECHNOLOGY
(EAE&AT)

MATLAB / SIMULINK SUMMER


TRAINING COARSE

Page:52

Exercise:
1- Define and plot the piecewise defined function:

2- write a subroutine called (chk_inv.m) that takes as input a square matrix and
returns its inverse (if it exists). Make use of the if statement. If the matrix is not
square or if it does
not have an inverse, the subroutine should print a message letting us know and it will terminate without
computing anything.
3- write an m-file called fact.m that gives the factorial of a positive number n = 1234
. . . (n - 1)n, using the recursive formula n! = n (n - 1).
4- Calculate the sum of elements in a vector x=1 to 5.

EGYPTIAN ACADEMY OF
ENGINEERING & ADVANCED
TECHNOLOGY
(EAE&AT)

MATLAB / SIMULINK SUMMER


TRAINING COARSE

Page:53

Lesson 5
Objectives:
-

Plotting 2-D graphs.


Plotting 3-D graphs.

Material:
Graph Plotting :
Two-dimensional graphics
1.
2.
3.
4.
5.
6.
7.
8.

The plot command


Plotting several curves on the same axes
Line types
Axis control
Labelling plots
Plotting several axes in the same graph window
Using several graph windows
Other types of plots

1. The plot command


To produce a graph of y = x2 for 0 < x < 1.
>> x = 0 : .01 : 1;
y = x.^2;
plot(x,y)

EGYPTIAN ACADEMY OF
ENGINEERING & ADVANCED
TECHNOLOGY
(EAE&AT)

MATLAB / SIMULINK SUMMER


TRAINING COARSE

Page:54

2. Plotting several curves on the same axes


To produce plots of the curves y = x, y = x2, y = x3, and y = x4 on the same graph.
x = 0 : .01 : 1;
y1 = x; y2 = x.^2; y3 = x.^3; y4 = x.^4;
plot(x,y1, x,y2, x,y3, x,y4)

If several curves are to be plotted simultaneously, and if they all use the same
vector of horizontal coordinates, then another method can be used to plot the
curves. The following sequence of commands produces the same result as the
preceding example.

>> x = 0 : .01 : 1;
Y = [x; x.^2; x.^3; x.^4];
plot(x,Y)
3. Line types

EGYPTIAN ACADEMY OF
ENGINEERING & ADVANCED
TECHNOLOGY
(EAE&AT)

>>
>>
>>
>>

MATLAB / SIMULINK SUMMER


TRAINING COARSE

Page:55

When you plot a curve, it


is possible to specify any of several
different line types. Suppose that the horizontal and vertical coordinates are
contained in vectors x and y, respectively. Some commands:
plot(x,y,'-')
Plot a solid curve.
plot(x,y,'--')
Plot a dashed curve.
plot(x,y,':')
Plot a dotted curve.
plot(x,y,'-.')
Plot a dash-dot curve.

Example:
>> x = 0 : .01 : 1;
y1 = x; y2 = x.^2;
plot(x,y1,'-.', x,y2, ':')

An alternative is to produce point plots, in which the data points are plotted but are
not connected by curves. To mark the points with small circles, use o as the third
argument in the plot command; for asterisks, use *; for xs, use x; for plusses,
use +; for dots, use . .

Example:
>> x = 0 : .01 : 1;
y1 = x; y2 = x.^2;
plot(x,y1,'x', x,y2, 'o')

EGYPTIAN ACADEMY OF
ENGINEERING & ADVANCED
TECHNOLOGY
(EAE&AT)

MATLAB / SIMULINK SUMMER


TRAINING COARSE

Page:56

If you are working on a


machine that has a color monitor, it is also
possible to specify the colors of curves and data points. E.g., r: for red, b: for blue; as
shown below. For more information, type help plot .
>> y1 = x; y2 = x.^2;
plot(x,y1,'bx', x,y2,

4. Axis control
The axis command can be used to control the ranges of x- and y-coordinates that are
plotted. (Unless you say otherwise, Matlab will choose the ranges automatically). For
example, the command
>> axis([0 10 -1 1])
specifies that the graph window will show the region 0x 10 , 1 y 1. The same effect
is obtained by the sequence of commands
>> v = [0 10 -1 1]; axis(v)
The axis command should be invoked after the graph is plotted. In general, it is possible
to plot a graph once and then execute the axis command several times to alter the
appearance of the plot.
Example: The following statements produce graphs of y = x and y = x2 for 0 < x < 2. In
this plot, the line y = x intersects the horizontal axis at angle 45. The angle would be
different if the command axis(equal) were not executed. The command axis(square)
forces the graph box to be square, which otherwise would not be the case.
>>
>>
>>
>>

x = 0 : .1 : 2;
plot(x, x.^2)
axis('equal')
axis('square')

EGYPTIAN ACADEMY OF
ENGINEERING & ADVANCED
TECHNOLOGY
(EAE&AT)

MATLAB / SIMULINK SUMMER


TRAINING COARSE

Page:57

5. Labeling plots
Suppose that a plot is currently residing in the graphics window. Some commands:
xlabel(info) Place the character string info immediately below the x-axis.
ylabel(info) Place the character string info next to the y-axis.
title(info) Place the character string info above the graph.
The function text can be used to place a character string at an arbitrary position on the
plot. If x and y are scalars, the command text(x,y,info) places the lower left corner of
the character string info at position (x,y) in the graphics screen, where x and y are
measured in the units of the current plot. For more information about text, type help text .
The function gtext is similar to text, except that the text is placed graphically. Execute
the command gtext(info), use the mouse to move the pointer to the desired location in
the graph window, and then press any mouse button or any key. The lower left corner of
the character string info is then placed at that position.
6. Plotting several axes in the same graph window
It is possible to divide the graph window into several subwindows and then place a plot in
each subwindow. The command subplot(m,n,p) divides the graph window into an mn
array of subwindows and then selects the pth subwindow for the next plot.
Example: Display the graphs of y = x, y = x2, y = x3, and y = x4 in a 22 array of plots.
x = 0 : .01 : 1;
% Divide the graph window into a 2x2 array of windows, and
% and plot y = x in the first window.
subplot(2,2,1)
plot(x, x)
title('y = x')
% Place plots in the other windows. Several commands
% can be placed on one line.
subplot(2,2,2), plot(x, x.^2), title('y = x^2')
subplot(2,2,3), plot(x, x.^3), title('y = x^3')
subplot(2,2,4), plot(x, x.^4), title('y = x^4')
% Go back and put y-labels on the first and fourth plots.
subplot(2,2,1), ylabel('first plot')
subplot(2,2,4), ylabel('last plot')

EGYPTIAN ACADEMY OF
ENGINEERING & ADVANCED
TECHNOLOGY
(EAE&AT)

MATLAB / SIMULINK SUMMER


TRAINING COARSE

Page:58

7. Using several graph windows


The command figure is used to create a new window for each plot command.
Example: Suppose that the only open graphics window is Figure No. 1 . The following
commands plot the graph of y = x in Figure No. 1 , y = x 2 in Figure No. 2 , and y = x 3 in
Figure No. 3 . The third figure is then printed.
x = 0 : 0.01 : 1;
y = x;
plot(x,y)
figure, plot(x, x.^2)
figure, plot(x, x.^3)

Three separate windows will be created for each plot.


8. Other types of plots
1- Parametric plots can be produced by using the plot command.
Example: Graph the spiral curve x = t cos t, y = t sin t for 0 < t < 2 . The command
axis(equal) eliminates the distortion that would have occurred due to different horizontal
and vertical scales, and the command axis([-7 7 -7 7]) causes the point (0, 0) to be in the
center of the graph window.
t = 0 : .01 : 2*pi;
x = t.*cos(t); y = t.*sin(t);
plot(x,y)
axis('equal'), axis([-7 7 -7 7]), axis('square')

EGYPTIAN ACADEMY OF
ENGINEERING & ADVANCED
TECHNOLOGY
(EAE&AT)

MATLAB / SIMULINK SUMMER


TRAINING COARSE

Page:59

2- Logarithmic plots are also possible. The following commands are used in the same
manner as plot, and they yield the indicated results.
Loglog
Semilogx
Semilogy

x- and y-axes are logarithmic.


x-axis is logarithmic, y-axis is linear.
y-axis is logarithmic, x-axis is linear.

Example: Create a simple loglog plot with square markers.


x = 0:.1:10;
loglog(x,10.^x,'-s')

grid on
graph.

%The command grid can be used to draw a grid on the

3- The polar command is used to produce polar plots. In the argument list, list the angle
(in radians) and then the radius. The polar command will not accept multiple plots, so it
will be necessary to use the hold command if you want more than one curve in the same
plot.
Example: Graph the curves = cos 2and = cos 4 for 0 2. The second curve is
plotted as a dotted curve.

EGYPTIAN ACADEMY OF
ENGINEERING & ADVANCED
TECHNOLOGY
(EAE&AT)

MATLAB / SIMULINK SUMMER


TRAINING COARSE

Page:60

theta = 0 : .01 : 2*pi;


rho2 = cos(2*theta); rho4 = cos(4*theta);
polar(theta, rho2)
hold on, polar(theta,rho4,':'), hold off
title('polar plot')

The function fplot can be used to plot functions that are defined symbolically; Matlab will
choose the sample points for you. However, the function needs to be defined in an M-file.
Example: Suppose that a file named fsqr.m is located in a directory in Matlabs search
path, and suppose that this file consists of the following statements.
function y = fsqr(x)
y = x.^2;
If you then execute the command fplot(fsqr, [0 10]) in your Matlab session, the result is
a graph of y = x2 for 0 > x > 10. Various options are available; type help fplot.
Note that: More details about 2D graphs are available on
>>help plotxy
This help message includes the routines semilogx which plots graphs where the x axis is
scaled logarithmically; semilogy, where the y axis is scaled logarithmically and loglog
where the graph is plotted where both axes are scaled logarithmically. It is also possible
to plot bargraphs, histograms, etc. Details about each specific function are available, for
instance, to learn more about loglog, you type
>>help loglog
When showing two graphs on the same axes it is convenient to write a label for each. The
command text (x, y, str) writes the string str at position x,y.
Example:
t=pi*[0:0.1:2];
plot(t,sin(t));
The first command fills the array with values at suitable intervals. The second sends to
the plot command two arrays, the first has the values for co-ordinates in the x direction,
the second the values in the y direction. These values will be plotted on a graph, suitably

EGYPTIAN ACADEMY OF
ENGINEERING & ADVANCED
TECHNOLOGY
(EAE&AT)

scaled, with axes marked with


added:
title('Sine graph');
the graph
xlabel('t');
ylabel('func');

MATLAB / SIMULINK SUMMER


TRAINING COARSE

Page:61

appropriate scales. Information

can

be

%adds the string Sine graph as a title to


%labels the x axis as t
%labels the y axis as func

Two graphs can be plotted superimposed. For instance,


t=pi*[0:0.1:2];
plot(t,sin(t),t,cos(t));

Plots the graph of sin(t) against t, and the graph of cos(t) against t. Note there must be
pairs of x and y co-ordinates for each graph. Three graphs can be plotted by including
three pairs of co-ordinates, etc.
MATLAB chooses suitable colours and ways of representing the data on the graphs. By
default, graphs are series of lines joined up, and different colours are used for each plot.
These can be overriden, for instance,
plot(t,sin(t),'y-',t,cos(t),'black*');

EGYPTIAN ACADEMY OF
ENGINEERING & ADVANCED
TECHNOLOGY
(EAE&AT)

MATLAB / SIMULINK SUMMER


TRAINING COARSE

Page:62

Specifies that the sine graph should be lines in white and the cosine graph should be a
series of yellow asterixes. A full list of the available colours and means of representing the
lines is available by typing
>>help plot
As the subplot function allows two or more graphs to be drawn on separate axes.
>>subplot(r,c,g);
specifies that there will be r*c graphs, arranged in r rows and c columns, and that the
next graphics command will apply to graph number g. The following shows how two
graphs are shown, one of sin(t) at the top, and one of exp(-t)*sin(t) on the bottom.
t=pi*[0:0.1:2];
subplot(2,1,1);
plot(t,sin(t));
title('Sinusoid');
subplot(2,1,2);
plot(t,exp(-t).*sin(t));
title('Exponentially damped sinusoid');

EGYPTIAN ACADEMY OF
ENGINEERING & ADVANCED
TECHNOLOGY
(EAE&AT)

MATLAB / SIMULINK SUMMER


TRAINING COARSE

Page:63

The first call to plot and to title


apply to the top graph region. The second
call to plot and title apply to the bottom graph region. Note the use of the .* operator to
calculate exp(-t)*sin(t). The function clf clears the graphics window and sets it to having
region for one graph.
Type: clf

Animations
The simplest way to produce an animated picture is with comet, which produces a parametric plot of a curve (the
way plot does), except that you can see the curve being traced out in time. For example,
t = 0:0.01*pi:2*pi;
figure; axis equal; axis([-1 1 -1 1]); hold on
comet(cos(t), sin(t))

Displays uniform circular motion .For more complicated animations; you can use getframe and movie. The
command getframe captures the active figure window for one frame of the movie, and movie then plays back
the result. For example, the following (in MATLAB 5.3 or later earlier versions of the software used a slightly
different syntax) produces a movie of a vibrating string:
x = 0:0.01:1;
for j = 0:50
plot(x, sin(j*pi/5)*sin(pi*x)), axis([0, 1, -2, 2])
M(j+1) = getframe;
end

EGYPTIAN ACADEMY OF
ENGINEERING & ADVANCED
TECHNOLOGY
(EAE&AT)
movie(M)

MATLAB / SIMULINK SUMMER


TRAINING COARSE

Page:64

Three-dimensional graphics
1.
2.
3.
4.
5.

Defining arrays of independent and dependent variables


Contour plots
Plotting implicit functions
Surface plots
Parametric plots

1. Defining arrays of independent and dependent variables


Suppose that you want to plot a function of (x, y) for 0 > x > 1.5 and 0 > y > 1 , with
increment 0.5 in each variable. (In practice, the increment should generally be much
smaller than this). Arrays containing values of these variables are generated by the
following commands.
x = 0 : 0.5 : 1.5;
y = 0 : 0.5 : 1;
[X,Y] = meshgrid(x,y)
[X,Y] = meshgrid(x,y) transforms the domain specified by vectors x and y into arrays X
and Y, which can be used to evaluate functions of two variables and three-dimensional
mesh/surface plots. The rows of the output array X are copies of the vector x; columns of
the output array Y are copies of the vector y.
Recall that Matlab is case-sensitive, so that X is not the same as x. The output from the
meshgrid command is as follows.

2. Contour plots
The Matlab function contour produces contour plots of functions of two real variables; the
Matlab function contour3 produces three-dimensional contour plots, in which contours are
placed on a three-dimensional surface. Information about these and other facilities can be
obtained via the help menu; for example, try help plotxyz, and help graphics.
Example: Here, we produce a contour plot of the surface z = ey sin x for 0 x and 0
y 1.
>> x = 0 : pi/30 : pi;

EGYPTIAN ACADEMY OF
ENGINEERING & ADVANCED
TECHNOLOGY
(EAE&AT)

MATLAB / SIMULINK SUMMER


TRAINING COARSE

Page:65

y = 0 : .1 : 1;
[X,Y] = meshgrid(x,y);
Z = exp(-Y) .* sin(X);
contour(Z)

The first four statements produce values of z on a rectangular grid. On this grid, x varies
from 0 to in increments of /30, and y varies from 0 to 1 in increments of 0.1. The last
statement produces a contour plot. In this plot, the contour curves are not labelled, and
the coordinate axes are labelled by matrix indices, not by values of the actual coordinates
x and y. Matlab chooses the values of z for which contours are plotted.
Example: In the preceding example, replace the statement contour(Z) with contour
(x,y,Z). In the resulting plot, the horizontal coordinate is labelled as varying from 0 to ,
and the vertical coordinate is labelled as varying from 0 to 1. The contour curves are not
labelled, and the contour interval is chosen by Matlab.
x = 0 : pi/30 : pi;
y = 0 : .1 : 1;
[X,Y] = meshgrid(x,y);
Z = exp(-Y) .* sin(X);
contour(x,y,Z)

EGYPTIAN ACADEMY OF
ENGINEERING & ADVANCED
TECHNOLOGY
(EAE&AT)

MATLAB / SIMULINK SUMMER


TRAINING COARSE

Page:66

Example: In this example, the


contour levels are specified explicitly, and
each contour is labelled with the corresponding value of z.
x = 0 : pi/30 : pi;
y = 0 : .1 : 1;
[X,Y] = meshgrid(x,y);
Z = exp(-Y) .* sin(X);
v = .2 : .2 : 1;
cdata = contour(x,y,Z,v);
clabel(cdata)

The vector v contains the values of z for which contours are to be drawn. In general, these
values do not need to be evenly spaced, nor do they need to be given in any particular
order. The statement cdata = contour(x,y,Z,v); produces the plot and stores data about
the plot in an array named cdata . (It is not necessary to use the name cdata for this
array.) The semicolon at the end of this statement is used to suppress printing of the
array. For information about what is stored in the array, type help contourc at the Matlab
prompt.
The final statement clabel(cdata) produces labels of the contour curves. Matlab
chooses the positions to place the labels, and each curve is labelled at least once. If you
wish to choose the positions yourself, use the statement clabel(cdata,manual) instead
of clabel(cdata). Use the mouse to point to positions on the contour curves where labels
are to be placed. Clicking the mouse places a label. To quit this mode, press the return
key.
3. Plotting implicit functions
One application of contour plotting is to plot curves that are defined implicitly. If you want
to plot a curve of the form f(x, y) = 0, make a contour plot of f with one contour level z =
0.
Example: Plot the curve(s) defined by exy = (1 + x + y).
x = -5 : .1 : 5;
y = -5 : .1 : 5;
[X,Y] = meshgrid(x,y);
Z = exp(X.*Y) - (1 + X + Y);
v = [0 0];
contour(x,y,Z,v)

EGYPTIAN ACADEMY OF
ENGINEERING & ADVANCED
TECHNOLOGY
(EAE&AT)

MATLAB / SIMULINK SUMMER


TRAINING COARSE

Page:67

4. Surface plots
Matlab has several commands for plotting surfaces in three dimensions. Some
examples are the following.
mesh
Represent the surface as a wire-frame mesh.
Meshc
Represent the surface as a wire-frame mesh, and also display a contour
plot in the (x, y) plane.
surf
Same as mesh, except that the panes between the mesh curves are
colored (or shaded).
surfc
Same as surf, except that a contour plot is also shown in the (x, y)
plane.
For more information on these and other facilities, consult the help menu, e.g., type help
plotxyz and help graphics . The functions xlabel, ylabel, zlabel, title, and text can be
used to label surface plots. Some aspects of the mesh and meshc functions are
illustrated in the following examples. The surf and surfc functions are used in the same
manner.
Example: Here, we produce a mesh plot of the surface z = ey sin x for 0 x and 0 y
1.
x = 0 : pi/30 : pi;
y = 0 : .1 : 1;
[X,Y] = meshgrid(x,y);
Z = exp(-Y).*sin(X);
mesh(Z), xlabel('x'), ylabel('y'), zlabel('z')

EGYPTIAN ACADEMY OF
ENGINEERING & ADVANCED
TECHNOLOGY
(EAE&AT)

MATLAB / SIMULINK SUMMER


TRAINING COARSE

Page:68

In this plot, the origin is closest to the observer, the x-axis points to the right and
into the background, the y-axis points backward and to the left, and the z-axis points
upward. The x- and y-axes are labelled by matrix indices, not by the actual coordinate
values.
Example: In the preceding example, replace the last line with mesh(x,y,Z), xlabel(x),
ylabel(y), zlabel(z) In this case, the horizontal axes are labelled according to the true
coordinate values. However, the x-axis might be longer than the interval [0, ]. If you
want to make sure that the x-axis extends only over the interval [0, ], type axis([0 pi 0 1
0 1]) after the
graph has been plotted.
x = 0 : pi/30 : pi;
y = 0 : .1 : 1;
[X,Y] = meshgrid(x,y);
Z = exp(-Y).*sin(X);
mesh(x,y,Z), xlabel('x'), ylabel('y'), zlabel('z')
axis([0 pi 0 1 0 1])

EGYPTIAN ACADEMY OF
ENGINEERING & ADVANCED
TECHNOLOGY
(EAE&AT)

MATLAB / SIMULINK SUMMER


TRAINING COARSE

Page:69

The position from which the graph is viewed is set by

>>view(az, el)
where az is the azimuth rotation and el is the vertical elevation, both in degrees. In the
figure below, az = -60 and el =10
Example: The function view can be used to change the point from which the surface is
viewed.
mesh(x,y,Z), xlabel('x'), ylabel('y'), zlabel('z')
axis([0 pi 0 1 0 1])
view(120,30)

In this example, the x-axis points forward and to the left, the y-axis points to the
right, and the z-axis points upward. In general, the first argument in function view is an
angle of rotation (in degrees) about the z-axis, and the second argument is an angle of
elevation above or below the (x, y) plane. If the first argument is zero, then the x-axis
points to the right, and the y-axis points into the background. Positive values of the first
argument indicate counterclockwise rotation of the observer, as viewed from the positive
z-axis. The default value of the first argument is -37.5. The default angle of elevation is
30; positive values mean that the observer is above the (x, y) plane.
Example: For x, y, and Z defined in the previous example.
meshc(x,y,Z), xlabel(x), ylabel(y), zlabel(z)
axis([0 pi 0 1 0 1])

EGYPTIAN ACADEMY OF
ENGINEERING & ADVANCED
TECHNOLOGY
(EAE&AT)

MATLAB / SIMULINK SUMMER


TRAINING COARSE

Page:70

The function meshc produces a mesh plot, just like the function mesh, and it also
creates a contour plot in the (x, y) plane. In this example, the default viewpoint is used,
but the viewpoint can be changed by using the view function.
6. Parametric plots
The functions plot3 and comet3 can be used to plot parametric curves in three
dimensions; consult the help items for these functions. The function comet is a two
dimensional analogue of comet3.
The mesh and surf functions can be used to plot surfaces for which z is not a function of x
and y. Instead, write x, y, and z as functions of two independent variables, and plot a
parametric surface.
Example: If the axis of a torus is the z-axis, then the torus can be parameterized in the
form x = (a + b cos ) cos , y = (a + b cos ) sin , z = b sin , for 0 2, 0 2.
Here, a is the distance from the z-axis to the center of a cross-section, b is the radius of a
cross-section, is an angle of rotation about the z-axis, and is an angle of rotation
within a cross-section. Here, we plot a torus for which a = 2 and b = 1.
theta = 0 : pi/16 : 2*pi;
psi = 0 : pi/16 : 2*pi;
[T, P] = meshgrid(theta, psi);
a = 2; b = 1;
X = ( a + b*cos(P) ) .* cos(T);
Y = ( a + b*cos(P) ) .* sin(T);
Z = b*sin(P);
mesh(X,Y,Z)
axis([-3, 3, -3, 3, -3, 3])
axis('square')

EGYPTIAN ACADEMY OF
ENGINEERING & ADVANCED
TECHNOLOGY
(EAE&AT)

MATLAB / SIMULINK SUMMER


TRAINING COARSE

Page:71

If the axis commands were not executed, then the default scaling of axes would be used,
and the cross-sections of the torus would appear to be ellipses. With the given sequence
of commands, the cross-sections are approximately circular.
theta = 0 : pi/16 : 2*pi;
psi = 0 : pi/16 : 2*pi;
[T, P] = meshgrid(theta, psi);
a = 2; b = 1;
X = ( a + b*cos(P) ) .* cos(T);
Y = ( a + b*cos(P) ) .* sin(T);
Z = b*sin(P);
mesh(X,Y,Z)

MATLAB has quite a powerful set of graph plotting routines, for both 2D and 3D
graphs. The following two commands illustrate how a simple graph could be plotted.
The colour of the data plotted is determined by the range of values in z. If just a black
white graph is needed, the colormap must be set to black. There is no command 'black',
but there is one called 'white' which produces a vector of '1's. Thus black is 1-white: so
>> colormap(1-white)

EGYPTIAN ACADEMY OF
ENGINEERING & ADVANCED
TECHNOLOGY
(EAE&AT)

MATLAB / SIMULINK SUMMER


TRAINING COARSE

Page:72

3D plotting
Three dimensional graphs are possible, more details being available using
>>plotxyz
The simplest plot function for three dimensions is plot3(x,y,z) where x, y and z are
matrices containing data in the x, y and z directions. For instance, consider
t=pi*[1:0.1:10];
plot3(t,sin(t),cos(t))

These cause a helix to be plotted, as is shown in the figure below. Note, the x, y and z
axes can be labelled by the commands xlabel, ylabel and zlabel.

NOTE

You can edit any graph whatever needed interactively using the graph window as follows:

EGYPTIAN ACADEMY OF
ENGINEERING & ADVANCED
TECHNOLOGY
(EAE&AT)

MATLAB / SIMULINK SUMMER


TRAINING COARSE

Page:73

Edit meun > Figure Properties


The figure then is ready for editing any of its property. For example, the line color & type,
grid, axes range & font, text, zooming in & out, view angle, colormap, etc.

For more & more information, search "Types of MATLAB plots" in the MATLAB help.
Summary:
The following table describes the plotting manipulations:

Also, the next table illustrates the plots colors and styles:

EGYPTIAN ACADEMY OF
ENGINEERING & ADVANCED
TECHNOLOGY
(EAE&AT)

MATLAB / SIMULINK SUMMER


TRAINING COARSE

Page:74

Exercise:
1- Execute the following commands and try to understand how z is defined.
>>
>>
>>
>>
>>
>>

hold on
x = -3:0.05:3; y = sin(3*x);
subplot(1,2,1); plot(x,y); axis tight
z = (y < 0.5) .* y;
subplot(1,2,2); plot(x,y,'r:'); plot(x,z,'r'); axis tight
hold off

2- Generate two matrices from the original input data: one with all of the temperature
values in Celsius and the other with all of the temperature values in Fahrenheit.
Celsius
-5
-23
22
0
35
40
10
80
90
38
150
100

Fahrenheit
23
-10
72
32
95
104
50
176
194
100
302
212

Generate a labeled plot of Fahrenheit (y-axis) vs. Celsius (x-axis) temperature values.
Check: does your plot match the temperature conversion expression F 1.8C 32.

EGYPTIAN ACADEMY OF
ENGINEERING & ADVANCED
TECHNOLOGY
(EAE&AT)

MATLAB / SIMULINK SUMMER


TRAINING COARSE

Page:75

Lesson 6
Objectives:
-

Introduction to Simulink

Material:

As we simply started the MATLAB coarse to add & subtract 2 variables using the
MATLAB prompt, then M-file, we will start learning simulink from this point. Mathematical
manipulating for scalar variables, then for signals. Then we will learn plotting graphs
using Simulink. Also, the conditional statements, and loops can be achieved using
Simulink.
Simulink is a MATLAB Toolbox for modeling, simulating, and analyzing dynamic
systems. It supports linear and nonlinear systems, modeled in continuous time, sampled
time, or a hybrid of the two. Systems can also be multi-rate, i.e., have different parts that
are sampled or updated at different rates.
Simulink provides a graphical user interface (GUI) for building models as block
diagrams, using click-and-drag mouse operations. Simulink includes a comprehensive
block library of sinks, sources, linear and nonlinear components, and connectors. You can
also customize and create your own blocks.
After building the model it can be simulated either in Simulink or from the Matlab
Command Window. In Simulink you can analyze the results during the simulation with
scopes and display blocks. Simulation results can also be saved in MatLab Workspace for
further treatment and visualizing. Below you will find some basics about how to structure
your works in Simulink:

Blocks
A Simulink block is a subsystem with inputs and/or outputs. Inside the block a set of
rules relate the input to output. These rules can be almost anything you can think of. In
our context the relations could be Gain, Sum, Integration, Laplace transfer functions,
linear and nonlinear relations etc. just to give some examples from the Simulink library.

Models
A Simulink model is a connection of blocks, representing your functionality. Models
are hierarchical, so you can build models using both top-down and bottom-up approaches.
You can view the system at a high level, then double-click blocks to go down through the
levels to see increasing levels of model detail. This approach provides insight into how a
model is organized and how its parts interact.

EGYPTIAN ACADEMY OF
ENGINEERING & ADVANCED
TECHNOLOGY
(EAE&AT)

MATLAB / SIMULINK SUMMER


TRAINING COARSE

Page:76

Library
Simulink comes with a library of standard blocks called the Simulink block library.
These blocks are used in creating new models and then saving this as a new "model".
Libraries also enable users to copy blocks into their models from external libraries and
automatically update the copied blocks when the source blocks change. Using libraries
allows users who develop their own block libraries.

Workspace
MATLAB Workspace is an important part of Simulink. This enables you to control
important variables inputting data to your model and collecting simulation data for further
treatment and visualization.

Building a Model
The objective of this lesson is to give a thorough insight in Simulink, the commands and
functions used in building models.
This lesson will discuss:
How to start Simulink from MatLab
How to build a simple model
How to control a simulation and visualizing the results
How to change the cosmetic in a model
Knowledge of some details in using the mouse
How is the anatomy of a block and how to edit
General considerations:
Starting from the Matlab Command Window, there are three ways of starting Simulink:
You can click the Simulink icon
in the toolbar
You can write the command simulink at the MatLab prompt
You can specify an existing Simulink file. Right now you should choose one of the
above.
This will open the Simulink Library Browser:

EGYPTIAN ACADEMY OF
ENGINEERING & ADVANCED
TECHNOLOGY
(EAE&AT)

MATLAB / SIMULINK SUMMER


TRAINING COARSE

Page:77

You can change the appearance from View in the toolbar. The number of libraries will
depend on the number of extensions included in your installation. Try to browse some of
the sublibraries to see the blocks included.
Building Simulink models and solutions
Example:
This example shows you how to build a model using many of the model-building
commands and actions you will use to build your own models. The instructions for
building this model in this section are brief. For more details you should always refer to
the
help
function.
This model integrates a sine wave and displays the result along with the sine wave. The
block diagram of the model looks like this.

To create a new model, click the New Model button


Simulink opens a new model window.

in the Library Browser's toolbar and

EGYPTIAN ACADEMY OF
ENGINEERING & ADVANCED
TECHNOLOGY
(EAE&AT)

MATLAB / SIMULINK SUMMER


TRAINING COARSE

Page:78

To create this model, you need to copy blocks into the model from the following Simulink
block libraries:
Sources library (the Sine Wave block)
Sinks library (the Scope block)
Continuous library (the Integrator block)
Signal Routing library (the Mux block)
To copy the Sine Wave block from the Library Browser, first expand the Library Browser
tree to display the blocks in the Sources library. Do this by clicking the Sources node.
Finally, click the Sine Wave node to select the Sine Wave block.
Here is how the Library Browser should look after you have done this.

Now drag a copy of the Sine Wave block from the browser and drop it in the model
window.

EGYPTIAN ACADEMY OF
ENGINEERING & ADVANCED
TECHNOLOGY
(EAE&AT)

MATLAB / SIMULINK SUMMER


TRAINING COARSE

Page:79

Copy the rest of the blocks in a


similar manner from their respective
libraries into the model window. You can move a block from one place in the model
window to another by dragging the block. You can move a block a short distance by
selecting the block, then pressing the arrow keys.
With all the blocks copied into the model window, the model should look something like
this.

If you examine the blocks, you see an angle bracket on the right of the Sine Wave block
and two on the left of the Mux block. The > symbol pointing out of a block is an output
port; if the symbol points into a block, it is an input port. A signal travels out of an output
port and into an input port of another block through a connecting line. When the blocks
are connected, the port symbols disappear.
Now it's time to connect the blocks. Connect the Sine Wave block to the top input port of
the Mux block. Position the pointer over the output port on the right side of the Sine Wave
block. Notice that the cursor shape changes to crosshairs.
Hold down the mouse button and move the cursor to the top input port of the Mux block.
Notice that the line is dashed while the mouse button is down and that the cursor shape
changes to double-lined crosshairs as it approaches the Mux block.
Now release the mouse button. The blocks are connected. You can also connect the line to
the block by releasing the mouse button while the pointer is over the block. If you do so,
the line is connected to the input port closest to the cursor's position.
Now the model looks like this:

If you look again at the model at the beginning of this section, you'll notice that most of
the lines connect output ports of blocks to input ports of other blocks. However, one line
connects a line to the input port of another block. This line, called a branch line, connects
the Sine Wave output to the Integrator block, and carries the same signal that passes
from the Sine Wave block to the Mux block.
Drawing a branch line is slightly different from drawing the line you just drew. To weld a
connection to an existing line, follow these steps:

EGYPTIAN ACADEMY OF
ENGINEERING & ADVANCED
TECHNOLOGY
(EAE&AT)

Position the pointer on the


block.

MATLAB / SIMULINK SUMMER


TRAINING COARSE

Page:80

line between the Sine Wave and the Mux

Press and hold down the Ctrl key (or click the right mouse button). Press the mouse
button, then drag the pointer to the Integrator block's input port or over the Integrator
block itself.
Release the mouse button. Simulink draws a line between the starting point and the
Integrator block's input port.
Now the model looks like this:

Finish making block connections. When you're done, your model should look something
like this:

Now set up Simulink to run the simulation for 10 seconds. First, open the Configuration
Parameters dialog box by choosing Configuration Parameters from the Simulation
menu. On the dialog box that appears, notice that the Stop time is set to 10.0 (its
default value and exactly what we need).

EGYPTIAN ACADEMY OF
ENGINEERING & ADVANCED
TECHNOLOGY
(EAE&AT)

MATLAB / SIMULINK SUMMER


TRAINING COARSE

Page:81

Close
the
Configuration
Parameters dialog box by clicking the OK
button. Simulink applies the parameters and closes the dialog box
Now double-click the Scope block to open its display window. Finally, choose Start from
the Simulation menu or click
Scope.

in the toolbar and watch the simulation output on the

The simulation stops when it reaches the stop time specified in the Configuration
Parameters dialog box or when you choose Stop from the Simulation menu or click the
Stop button on the model window's toolbar.
To save this model, choose Save from the File menu and enter a filename and location.
That file contains the description of the model.
Here is a short overview of the scope facilities:
The Scope provides toolbar buttons that enable you to zoom in on displayed data, display
all the data input to the Scope, preserve axis settings from one simulation to the next,
limit data displayed, and save data to the workspace. The toolbar buttons are labelled in
this figure, which shows the Scope window as it appears when you open a Scope block

EGYPTIAN ACADEMY OF
ENGINEERING & ADVANCED
TECHNOLOGY
(EAE&AT)

To

add

Click

multi-

the

button,

the

MATLAB / SIMULINK SUMMER


TRAINING COARSE

Page:82

inputs to the scope:


Scope
Parameters
following
window
appears,
for
the

General tab:

to simulate all data, from the Scope Parameters button, the following window appears, for
the Data History tab ,

EGYPTIAN ACADEMY OF
ENGINEERING & ADVANCED
TECHNOLOGY
(EAE&AT)

uncheck Limit data points to

MATLAB / SIMULINK SUMMER


TRAINING COARSE

Page:83

last check box.

Note: you can also check the Save data to workspace checkbox to save the data in the
workspace. Select 'Array' from the 'Format' to save the scope data in the workspace, to
be available to be used againconsidering that it should be one axis scope, as shown in the
figure below:

Also, if it is desired edit the Number of axes to the desired number of inputs, ex : 2 so the
scope outputs appears as follows"

Now open you model and try some of the following:


Changing some of the cosmetics
Blocks not in line: choose the block to move. Press and hold the left mouse botton
while moving it. Release the botton.
Enlarge blocks: click the block, pont at a corner and drag with the left mouse botton
Lines which is not perpendicular: choose the corner you want to move. Press and
hold the left mouse botton while moving it. Release the botton.

EGYPTIAN ACADEMY OF
ENGINEERING & ADVANCED
TECHNOLOGY
(EAE&AT)

MATLAB / SIMULINK SUMMER


TRAINING COARSE

Page:84

Delete a line: click the line


to delete and press the DEL botton.
Move a line: click the line. Press and hold the left mouse botton while moving it.
Release the botton. (Note that the original line is remaining until releasing the botton).
Using the mouse
One of the first things you will discover working with the mouse in Simulink is, that it's
contexts sensitive. This means that it will react different depending of what is pointed at.
This is how it works:
Working with Blocks:
left key: used to select and move a block
right key: used to copy a block, note that the cursor changes to a solid + and a copy
is created where you release the mouse
double: opens the dialog box where relevant parameters can be written
both: multi select, corresponds to holding the SHIFT key while using the left key).
Alternatively pres the left key while dragging a square around the elements you want
to select.
Working with lines:
left key:
clicking a line: selects the line
clicking the end of a line: further elements can be connected
clicking a corner of a line: the corner can be moved.
right key: is used for creating a new connection on the line.
both: removes snap
Working with text elements:
left key: select, move and change text
right key: same as left
left double click: add text (can be done anywhere on the sheet)
Changing blocks
After selecting a block you can change the appearance by choosing Format in the Toolbar
or by right clicking.
Double click will open a window with the Block Parameters (choosing Help will describe in
details).

EGYPTIAN ACADEMY OF
ENGINEERING & ADVANCED
TECHNOLOGY
(EAE&AT)

Examples

on

Building

MATLAB / SIMULINK SUMMER


TRAINING COARSE

Page:85

models:

Example:

Solution:
Construct the Simulink model as follows:

Use the 'Simulink' toolbar ; 'Commonly Used Blocks', to add the following blocks:
'Constant' and 'Mux' blocks.
Add the 'Scope' and 'Display' blocks from the Sinks in 'Simulink' toolbar.

The simulation time is set by default = 10.0sec. Press 'run' button.

Example:

EGYPTIAN ACADEMY OF
ENGINEERING & ADVANCED
TECHNOLOGY
(EAE&AT)

MATLAB / SIMULINK SUMMER


TRAINING COARSE

Page:86

The scope out of the 'Mux' block displays:

Example:
Consider a system with a spring, spring constant k and a mass m affected by a force f.
The equation of motion is:
2

d
m. 2 y+ k . y =f
dt

EGYPTIAN ACADEMY OF
ENGINEERING & ADVANCED
TECHNOLOGY
(EAE&AT)

MATLAB / SIMULINK SUMMER


TRAINING COARSE

Page:87

y is the displacement in
relation to equilibrium when influenced by
f. This system is modeled in Simulink in the following manner. k and f is assumed to be 1.

a) Build this system in Simulink.


Hint:
Change the sign in the Add block by double clicking the block
b) Examine how the system reacts when a unity step is applied as an input.
Hint:
Use the Step block from Sources library.
c) Examine how the system reacts when a square wave is applied with the frequency of 5
rad/sec.
Hint:
Use the Signal Generator in Sources to generate the input signal.
Solution:
a. Simulink model:

EGYPTIAN ACADEMY OF
ENGINEERING & ADVANCED
TECHNOLOGY
(EAE&AT)

MATLAB / SIMULINK SUMMER


TRAINING COARSE

The scope displays:

b. Simulink model with unity step as input and Scope as output:

Page:88

EGYPTIAN ACADEMY OF
ENGINEERING & ADVANCED
TECHNOLOGY
(EAE&AT)

Output on the Scope, after clicking the fieldglasses:

c. Simulink model with square wave input:

MATLAB / SIMULINK SUMMER


TRAINING COARSE

Page:89

EGYPTIAN ACADEMY OF
ENGINEERING & ADVANCED
TECHNOLOGY
(EAE&AT)

MATLAB / SIMULINK SUMMER


TRAINING COARSE

Page:90

Input (yellow) and Output (magenta) on the Scope:

Example:
Examine the time response for the system described by the following equation:
d
x =x +sin ( 10 x )+sin (t)
dt
Hints:

EGYPTIAN ACADEMY OF
ENGINEERING & ADVANCED
TECHNOLOGY
(EAE&AT)

MATLAB / SIMULINK SUMMER


TRAINING COARSE

To get the time t you choose


Clock from Sources.
The sine is created with a Fcn block from User-Defined Functions.
Solution:
Simulink model

:
Output on the Scope, after clicking the telescope:

Exercises:
1- Examine the unity step response for the following system:
d
x =x +u
dt
u is the input and x the output.
2- Examine the time response for the system :

Page:91

EGYPTIAN ACADEMY OF
ENGINEERING & ADVANCED
TECHNOLOGY
(EAE&AT)

MATLAB / SIMULINK SUMMER


TRAINING COARSE

Page:92

d
x =x + x 2
dt
with the initial conditions x(0) = 0.2.
Hints:
By double clicking the integrator block, you are asked for the initial condition.
Squaring is done with the Dot Product in Math Operations library. Connect both inputs
to the output
of the integrator (which is the x variable).
3- One of the really strong features in Simulink, is the possibility of building
parametric models. That means using a named variable instead of a specific
value. The only prerequisite is that the named variable must by assigned a value
in
MatLabs
Workspace
before
starting
the
simulation.
In that way it is possible to change the parameters and settings without being
forced to find the actual blocks.
a) Create a parametric model in Simulink for the following systems:
m.

d2
d
y+ c . y+ k . y =f
2
dt
dt

b) Run a simulation with m = 2 kg, c = 2.5 kg/sec and k = 40 N/m


c) Run a simulation with the new values m = 5 kg, c = 4 kg/sec og k = 10 N/m

Lesson 7
Conditional statements using Simulink:
1- If else statement:

Construct an if-else control flow diagram as follows:

Provide data inputs to the If block for constructing if-else conditions.

EGYPTIAN ACADEMY OF
ENGINEERING & ADVANCED
TECHNOLOGY
(EAE&AT)

MATLAB / SIMULINK SUMMER


TRAINING COARSE

Page:93

Inputs to the If block are


set in the If block properties dialog box.
Internally, they are designated as u1, u2,..., un and are used to construct output
conditions.

Set output port if-else conditions for the If block.


Output ports for the If block are also set in its properties dialog box. You use the
input values u1, u2, ..., un to express conditions for the if, elseif, and else condition
fields in the dialog box. Of these, only the if field is required. You can enter multiple
elseif conditions and select a check box to enable the else condition.

Connect each condition output port to an Action subsystem.


Each if, elseif, and else condition output port on the If block is connected to a
subsystem to be executed if the port's case is true. You create these subsystems by
placing an Action Port block in a subsystem. This creates an atomic Action
subsystem with a port named Action, which you then connect to a condition on the
If block. Once connected, the subsystem takes on the identity of the condition it is
connected to and behaves like an enabled subsystem.

Example:

2- S
wi
tc
h

case:

EGYPTIAN ACADEMY OF
ENGINEERING & ADVANCED
TECHNOLOGY
(EAE&AT)

MATLAB / SIMULINK SUMMER


TRAINING COARSE

Page:94

Construct a switch control flow statement as follows:

Provide a data input to the argument input of the Switch Case block.
The input to the Switch Case block is the argument to the switch control flow
statement. This value determines the appropriate case to execute. Noninteger
inputs to this port are truncated.

Add cases to the Switch Case block based on the numeric value of the argument
input.
You add cases to the Switch Case block through the properties dialog box of the
Switch Case block. Cases can be single or multivalued. You can also add an optional
default case, which is true if no other cases are true. Once added, these cases
appear as output ports on the Switch Case block.

Connect each Switch Case block case output port to an Action subsystem.
Each case output of the Switch Case block is connected to a subsystem to be
executed if the port's case is true. You create these subsystems by placing an
Action Port block in a subsystem. This creates an atomic subsystem with a port
named Action, which you then connect to a condition on the Switch Case block.
Once connected, the subsystem takes on the identity of the condition and behaves
like an enabled subsystem. Place all the block programming executed for that case
in this subsystem.

EGYPTIAN ACADEMY OF
ENGINEERING & ADVANCED
TECHNOLOGY
(EAE&AT)

MATLAB / SIMULINK SUMMER


TRAINING COARSE

Page:95

Loops
using

Simulink:
1- For loop:

EGYPTIAN ACADEMY OF
ENGINEERING & ADVANCED
TECHNOLOGY
(EAE&AT)

MATLAB / SIMULINK SUMMER


TRAINING COARSE

Example:
Using the for loop for matricies multiplication.

Double click to open 'For Each Subsystem' block:

Page:96

EGYPTIAN ACADEMY OF
ENGINEERING & ADVANCED
TECHNOLOGY
(EAE&AT)

Running the simulation:

2- Do-While:

MATLAB / SIMULINK SUMMER


TRAINING COARSE

Page:97

EGYPTIAN ACADEMY OF
ENGINEERING & ADVANCED
TECHNOLOGY
(EAE&AT)

MATLAB / SIMULINK SUMMER


TRAINING COARSE

Page:98

Simulink software repeatedly executes the contents of the While subsystem at each time
step until a condition specified by the While Iterator block is satisfied. In particular, for
each iteration of the loop specified by the While Iterator block, the Simulink software
invokes the update and output methods of all the blocks in the While subsystem in the
same order that the methods would be invoked if they were in a noniterated atomic
subsystem.
Construct a while loop as follows:

Place a While Iterator block in a subsystem.


The host subsystem's label changes to while {...} to indicate that it is modeling a
while loop. These subsystems behave like triggered subsystems. This subsystem is
host to the block programming you want to iterate with the While Iterator block.

Provide a data input for the initial condition data input port of the While Iterator
block.
The While Iterator block requires an initial condition data input (labeled IC) for its
first iteration. This must originate outside the While subsystem. If this value is
nonzero, the first iteration takes place.

Provide data input for the conditions port of the While Iterator block.
Conditions for the remaining iterations are passed to the data input port labeled
cond. Input for this port must originate inside the While subsystem.

You can set the While Iterator block to output its iterator value through its
properties dialog.
The iterator value is 1 for the first iteration and is incremented by 1 for each
succeeding iteration.

You can change the iteration of the While Iterator block to do-while through its
properties dialog.
This changes the label of the host subsystem to do {...} while. With a do-while
iteration, the While Iteration block no longer has an initial condition (IC) port,

EGYPTIAN ACADEMY OF
ENGINEERING & ADVANCED
TECHNOLOGY
(EAE&AT)

MATLAB / SIMULINK SUMMER


TRAINING COARSE

Page:99

because all blocks in the


subsystem are executed once before the
condition port (labeled cond) is checked.

Create a block diagram in the subsystem that defines the subsystem's outputs.

Example:

EGYPTIAN ACADEMY OF
ENGINEERING & ADVANCED
TECHNOLOGY
(EAE&AT)

MATLAB / SIMULINK SUMMER


TRAINING COARSE

Page:100

Double click to open 'While Iterator Subsystem':

Lesson 8
Choosing an equation solver

EGYPTIAN ACADEMY OF
ENGINEERING & ADVANCED
TECHNOLOGY
(EAE&AT)

MATLAB / SIMULINK SUMMER


TRAINING COARSE

Page:101

To simulate a block
diagram you have to choose a solver,
which means how to integrate and differentiate. The choice of method will depend on the
type of system you are dealing with. By default Simulink will make the choice for you and
make you running without much worrying.
This lesson we will end with some comments on equation solvers, and return to the
subject in the part concerning Numerical Methods.
Default equation solver: If you do not choose a solver, Simulink will do it for you.

If the model is continues an ode45 is chosen. This is a fantastic solver for most
systems but if your system is stiff or if you find the results suspicious then try an
ode15s

If the model is discrete Simulink will choose a solver named discrete


In general you can choose between variable or fixed steps
About Variable-Step Continuous Solvers:
Simulink variable-step solvers vary the step size during the simulation, reducing the
step size to increase accuracy when the states of a model are changing rapidly and
increasing the step size to avoid taking unnecessary steps when the model's states are
changing slowly. Computing the step size adds to the computational overhead at each
step, but can reduce the total number of steps, and hence the simulation time required
to maintain a specified level of accuracy for models with rapidly changing or piecewise
continuous states. Simulink provides the following variable-step continuous solvers:
ode45 is based on an explicit Runge-Kutta (4,5) formula, the Dormand-Prince pair. It is
a one-step solver; that is, in computing y(tn), it needs only the solution at the
immediately preceding time point, y(tn-1). In general, ode45 is the best solver to
apply as a first try for most problems. For this reason, ode45 is the default solver
used by Simulink for models with continuous states>

ode23 is also based on an explicit Runge-Kutta (2,3) pair of Bogacki and Shampine. It
can be more efficient than ode45 at crude tolerances and in the presence of mild
stiffness. ode23 is a one-step solver.

ode113 is a variable-order solver. It can be more efficient than ode45 at stringent


tolerances. ode113 is a multistep solver; that is, it normally needs the solutions at

EGYPTIAN ACADEMY OF
ENGINEERING & ADVANCED
TECHNOLOGY
(EAE&AT)

MATLAB / SIMULINK SUMMER


TRAINING COARSE

Page:102

several preceding time points to compute the current solution.

ode15s is a variable-order solver. Like ode113, ode15s is a multi-step method solver.


If you suspect that a problem is stiff, or if ode45 failed or was very inefficient, try
ode15s.

ode23s is a 2nd order solver. Because it is a one-step solver, it can be more efficient
than ode15s at crude tolerances. It can solve some kinds of stiff problems for which
ode15s is not effective. Use this solver if the problem is only moderately stiff and you
need a solution without numerical damping.

ode23tb. Like ode23s, this solver can be more efficient than ode15s at crude
tolerances.

discrete (variable step) is the equation solver Simulink will choose for discrete models
Note: For a stiff problem, solutions can change on a time scale that is very short
compared to the interval of integration, but the solution of interest changes on a much
longer time scale. Methods not designed for stiff problems are ineffective on intervals
where the solution changes slowly because they use time steps small enough to resolve
the fastest possible change.

Equation solvers with fixed step:


ode5 is a fixed-step version of ode45
ode4 is a 4. orden Runge-Kutta method
ode3 is a fixed-step version of ode23
ode2 is Heun's method, also known as an improved Euler
ode1 is Eulers metode
Exercise 1:
Build a Simulink model which has an output with a very slow varying frequency. This could
be:
y=sin ( 10. t +2 . cos ( 2. t ) )

Create a simulation with different solvers and find out which is the best i.e. right result
and smallest execution time.

EGYPTIAN ACADEMY OF
ENGINEERING & ADVANCED
TECHNOLOGY
(EAE&AT)

MATLAB / SIMULINK SUMMER


TRAINING COARSE

Page:103

Hint:
Use Clock and Fcn blocks to generate the output.
Solution 1:
Simulink model:

Simulation results (ode45 with max step size = 1e-2):

Comparison between the solvers (all with max step size = 1e-2):

Exercise 2:
Analyze the response from the system in the figure. Try to guess which solver is the best
(argue your choice) and afterwards make a try to verify your guess.

EGYPTIAN ACADEMY OF
ENGINEERING & ADVANCED
TECHNOLOGY
(EAE&AT)

MATLAB / SIMULINK SUMMER


TRAINING COARSE

Page:104

Hint:
Use the Switch block and Transfer Fcn. Input to the second Transfer Fcn is the output
from the first Transfer Fcn's output for the first 5 sec., after the input is 0
Solution 2:
Simulink model:

There is no significant difference in time constant for the two systems and intuitively
ode45 would be a good guess. ode45 gives this result:

A comparison of the solvers gives the following result:

EGYPTIAN ACADEMY OF
ENGINEERING & ADVANCED
TECHNOLOGY
(EAE&AT)

MATLAB / SIMULINK SUMMER


TRAINING COARSE

Page:105

If we just focus on the number of steps, we were right, buth others might be faster.

Excercise 3:
Analyze the response from the system below. Apply a step u = 10 at t = 0.1 sec.

Try ode45 and ode5, how do these two solvers differ from each other?

EGYPTIAN ACADEMY OF
ENGINEERING & ADVANCED
TECHNOLOGY
(EAE&AT)

MATLAB / SIMULINK SUMMER


TRAINING COARSE

Page:106

Solution 3:
Simulink model:

Simulating with ode45, and after clicking the telescope:

Simulating with ode5 :

It is obvious that ode5 (which uses fixed step) does not catch that something
drastic happens when the step is applied at t = 0.1 s.

Lesson 9
Creating Graphical User Interfaces

EGYPTIAN ACADEMY OF
ENGINEERING & ADVANCED
TECHNOLOGY
(EAE&AT)

MATLAB / SIMULINK SUMMER


TRAINING COARSE

Page:107

The Vision
All great software starts with a vision. One individual has an insight into a product he or she thinks would be
good to build. Rarely do committees create compelling visions. The very first phase of object-oriented analysis
and design is to capture this vision in a single sentence (or at most, a short paragraph). The vision becomes the
guiding principal of development, and the team that comes together to implement the vision ought to refer back
to itand update it if necessaryas it goes forward
Graphical User Interfaces (GUIs)
Unlike coding programs to accomplish tasks, the user of a GUI need not understand the details of how the tasks
are performed (User-friendly).
With MATLAB you can create your own Graphical User Interface, or GUI, which consists of a Figure window
containing menus, buttons, text, graphics, etc., that a user can manipulate interactively with the mouse and
keyboard. There are two main steps in creating a GUI: One is designing its layout, and the other is writing
callback functions that perform the desired operations when the user selects different features.
Where Do I Start?
Before starting to construct a GUI you have to design it. At a minimum, you have to decide:
Who the GUI users will be?
What you want the GUI to do?
How users will interact with the GUI?
What components the GUI requires to function?
What Is GUIDE?
GUIDE, the MATLAB Graphical User Interface Development Environment, provides a set of tools for creating
graphical user interfaces (GUIs). These tools greatly simplify the process of laying out and programming GUIs.
Starting (GUIDE)
To open GUIDE, select FileNewGUI from the Desktop menu bar or type guide in the Command Window.

If this is the first time you have run GUIDE, you will next see a window that encourages you to click on View
GUIDE Application Options dialog. We recommend that you do so to see what your options are, but leave the
settings as is for now.

EGYPTIAN ACADEMY OF
ENGINEERING & ADVANCED
TECHNOLOGY
(EAE&AT)

MATLAB / SIMULINK SUMMER


TRAINING COARSE

Page:108

After you click OK, the Layout Editor will appear, containing a large white area with a grid. As with most
MATLAB windows, the Layout Editor has a tool bar with shortcuts to many of the menu functions we describe
below

You will not see the name of the GUI components as seen in the figure above to do this you have to display the
names of the GUI components in the component palette. Select Preferences from the MATLAB File menu. Then
select GUIDE > Show names in component palette, and click OK. The Layout Editor then appears as shown in
the following figure.

Example:
For plotting a circle; we let the user enter the radius and the center distance from the x and y origin.

EGYPTIAN ACADEMY OF
ENGINEERING & ADVANCED
TECHNOLOGY
(EAE&AT)

MATLAB / SIMULINK SUMMER


TRAINING COARSE

Page:109

First open new GUI then set the layout as shown in the next figure
1. One axes
2. Two push buttons
3. One panel
a) Two edit text
b) Tow static text
4. One edit text
5. One static text
After adding the items of the GUI we must align them as shown either by placing them by the mouse or by using
the align object tool from the tools menu. To save the file, name it "iterator".
To change properties of an object such as its color, the text within it 'String', etc., you must open the
Property Inspector window. To do so, you can double-click on an object, or choose Property Inspector from the
Tools menu and then select the object you want to alter with the left mouse button. You can leave the Property
Inspector open throughout your GUIDE session and go back and forth between it and the Layout Editor.

GUI Callback Functions:


When you are ready to create a callback function for a given object:
Click the right mouse button on the object and select Edit Callback, or click the M-file icon in the
toolbar.
The M-file associated with the GUI will be brought to the front in an Editor/Debugger window.
A block of lines like the ones below will appear as shown below.
If you havent yet saved the GUI, you will be prompted to do so first, so that GUIDE knows what name
to give the M-file.
For pushbutton1:

EGYPTIAN ACADEMY OF
ENGINEERING & ADVANCED
TECHNOLOGY
(EAE&AT)

MATLAB / SIMULINK SUMMER


TRAINING COARSE

Page:110

We will add a command to the


pushbutton callback function which will close the
program. After following the steps above, the following lines will appear.
% --- Executes on button press in pushbutton1.
function pushbutton1_Callback(hObject, eventdata, handles)
% hObject
handle to pushbutton1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles
structure with handles and user data (see GUIDATA)

We will add a command to the pushbutton callback function which will read the radius, the center point
coordinates (x,y), then plot the circle.
% --- Executes on button press in pushbutton1.
function pushbutton1_Callback(hObject, eventdata, handles)
% hObject
handle to pushbutton1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles
structure with handles and user data (see GUIDATA)
x=str2double(get(handles.edit1,'string'));
y=str2double(get(handles.edit2,'string'));
r=str2double(get(handles.edit3,'string'));
%x=0.4,
%y=0.4;
%r=0.2;
i=1;
for th=0:.01:2*pi
x1(i)=r*cos(th)+x;
y1(i)=r*sin(th)+y;
i=i+1;
end
plot(x1,y1)
grid on

For pushbutton2:
To close the execution of this GUI when pressing this button, type:
close(iterate)
as shown below:
% --- Executes on button press in pushbutton1.
function pushbutton1_Callback(hObject, eventdata, handles)
% hObject
handle to pushbutton1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles
structure with handles and user data (see GUIDATA)
close(iterate)

To execute the file, press 'Run' button in the toolbar, the following window appears:

EGYPTIAN ACADEMY OF
ENGINEERING & ADVANCED
TECHNOLOGY
(EAE&AT)

MATLAB / SIMULINK SUMMER


TRAINING COARSE

Page:111

Enter the radius center coordinates (x,y), and the circle radius then press 'plot' button as shown below;

EGYPTIAN ACADEMY OF
ENGINEERING & ADVANCED
TECHNOLOGY
(EAE&AT)

Example 2:
(From GUI examples in the GUI help)

MATLAB / SIMULINK SUMMER


TRAINING COARSE

Page:112

EGYPTIAN ACADEMY OF
ENGINEERING & ADVANCED
TECHNOLOGY
(EAE&AT)

MATLAB / SIMULINK SUMMER


TRAINING COARSE

Page:113

Input Arguments
All callbacks in a GUIDE-generated GUI code file have the following standard input arguments:
1- hObject Handle of the object, e.g., the GUI component, for which the callback was triggered. For a
button group SelectionChangeFcn callback, hObject is the handle of the selected radio button or toggle
button.
2- eventdata Sequences of events triggered by user actions such as table selections emitted by a
component in the form of a MATLAB struct (or an empty matrix for components that do not generate
eventdata)
3- handles A MATLAB struct that contains the handles of all the objects in the GUI, and may also
contain application-defined data. See handles Structure for information about this structure.
1- Object Handle:
The first argument is the handle of the component issuing the callback. Use it to obtain relevant properties that
the callback code uses and change them as necessary. For example,
theText = get(hObject,'String');
places the String property (which might be the contents of static text or name of a button) into the local variable
theText. You can change the property by setting it, for example
set(hObject,'String',date)

EGYPTIAN ACADEMY OF
ENGINEERING & ADVANCED
TECHNOLOGY
(EAE&AT)

This particular code changes the text of

MATLAB / SIMULINK SUMMER


TRAINING COARSE

Page:114

the object to display the current date.

2- Event Data
Event data is a stream of data describing user gestures, such as key presses, scroll wheel movements, and mouse
drags. The auto-generated callbacks of GUIDE GUIs can access event data for Handle Graphics and uicontrol
and uitable object callbacks. The following ones receive event data when triggered:
CellEditCallback in a uitable
CellSelectionCallback in a uitable
KeyPressFcn in uicontrols and figures
KeyReleaseFcn in a figure
SelectionChangeFcn in a uibuttongroup
WindowKeyPressFcn in a figure or any of its child objects
WindowKeyReleaseFcn in a figure or any of its child objects
WindowScrollWheelFcn in a figure
Event data is passed to GUIDE-generated callbacks as the second of three standard arguments. For components
that issue no event data the argument is empty. For those that provide event data, the argument contains a
structure, which varies in composition according to the component that generates it and the type of event.
3- Handles Structure
GUIDE creates a handles structure that contains the handles of all the objects in the figure. GUIDE uses each
component's Tag property to name the structure element for its handle. GUIDE creates and maintains the handles
structure as GUI data. It is passed as an input argument to all callbacks and enables a GUI's callbacks to share
property values and application data.

Ex.,
set(handles.togglebutton1,'Value','Max')
puts the toggle button with Tag property togglebutton1 in the pressed state.
Getting User Input
The three edit text boxes are where the user enters values for the two frequencies and the time vector. The first
task for the callback is to read these values. This involves:

Reading the current values in the three edit text boxes using the handles structure to access the edit text
handles.

Converting the two frequency values (f1 and f2) from strings to doubles using str2double.

Evaluating the time string using eval to produce a vector t, which the callback used to evaluate the
mathematical expression.

EGYPTIAN ACADEMY OF
ENGINEERING & ADVANCED
TECHNOLOGY
(EAE&AT)

The following code shows how the

MATLAB / SIMULINK SUMMER


TRAINING COARSE

Page:115

callback obtains the input:

% Get user input from GUI


f1 = str2double(get(handles.f1_input,'String'));
f2 = str2double(get(handles.f2_input,'String'));
t = eval(get(handles.t_input,'String'));

Toggle Button
The callback for a toggle button needs to query the toggle button to determine what state it is in. The Value
property is equal to the Max property when the toggle button is pressed and equal to the Min property when the
toggle button is not pressed.
The following code illustrates how to program the callback.
function togglebutton1_Callback(hObject, eventdata, handles)
button_state = get(hObject,'Value');
if button_state == get(hObject,'Max')
% Toggle button is pressed, take appropriate action
...
elseif button_state == get(hObject,'Min')
% Toggle button is not pressed, take appropriate action
...
end
You can also change the state of a toggle button programmatically by setting the toggle button Value property
to the value of its Max or Min property. This example illustrates a possible syntax for such an assignment.
set(handles.togglebutton1,'Value','Max')
puts the toggle button with Tag property togglebutton1 in the pressed state.
Note You can use a button group to manage exclusive selection behavior for toggle buttons.

Radio Button
You can determine the current state of a radio button from within its Callback callback by querying the state
of its Value property. If the radio button is selected, its Value property is equal to its Max property. If the radio
button is not selected, it is equal to its Min property. This example illustrates such a test.
function radiobutton1_Callback(hObject, eventdata, handles)
if (get(hObject,'Value') == get(hObject,'Max'))
% Radio button is selected, take appropriate action
else
% Radio button is not selected, take appropriate action
end
You can also change the state of a radio button programmatically by setting the radio button Value property to
the value of the Max or Min property. This example illustrates a possible syntax for such an assignment.
set(handles.radiobutton1,'Value','Max')
selects the radio button with Tag property radiobutton1 and deselects the previously selected radio button.

EGYPTIAN ACADEMY OF
ENGINEERING & ADVANCED
TECHNOLOGY
(EAE&AT)

MATLAB / SIMULINK SUMMER


TRAINING COARSE

Page:116

Note You can use a button group to manage exclusive selection behavior for radio buttons.

Check Box
You can determine the current state of a check box from within its callback by querying the state of its Value
property. The Value property is equal to the Max property when the check box is checked and equal to the Min
property when the check box is not checked. This example illustrates such a test.
function checkbox1_Callback(hObject, eventdata, handles)
if (get(hObject,'Value') == get(hObject,'Max'))
% Checkbox is checked-take approriate action
else
% Checkbox is not checked-take approriate action
end
You can also change the state of a check box programmatically by setting the check box Value property to the
value of the Max or Min property. This example illustrates a possible syntax for such an assignment.
maxVal = get(handles.checkbox1,'Max');
set(handles.checkbox1,'Value',maxVal);
puts the check box with Tag property checkbox1 in the checked state.
Slider
You can determine the current value of a slider from within its callback by querying its Value property, as
illustrated in the following example:
function slider1_Callback(hObject, eventdata, handles)
slider_value = get(hObject,'Value');
% Proceed with callback...
The Max and Min properties specify the slider's maximum and minimum values. The slider's range is Max Min.
List Box
When the list box Callback callback is triggered, the list box Value property contains the index of the
selected item, where 1 corresponds to the first item in the list. The String property contains the list as a cell
array of strings.
This example retrieves the selected string. It assumes listbox1 is the value of the Tag property. Note that it is
necessary to convert the value returned from the String property from a cell array to a string.
function listbox1_Callback(hObject, eventdata, handles)
index_selected = get(hObject,'Value');
list = get(hObject,'String');
item_selected = list{index_selected}; % Convert from cell array
% to string
You can also select a list item programmatically by setting the list box Value property to the index of the
desired item. For example,
set(handles.listbox1,'Value',2)
selects the second item in the list box with Tag property listbox1.

EGYPTIAN ACADEMY OF
ENGINEERING & ADVANCED
TECHNOLOGY
(EAE&AT)

MATLAB / SIMULINK SUMMER


TRAINING COARSE

Page:117

Pop-Up Menu
When the pop-up menu Callback callback is triggered, the pop-up menu Value property contains the index
of the selected item, where 1 corresponds to the first item on the menu. The String property contains the menu
items as a cell array of strings.
Note A pop-up menu is sometimes referred to as a drop-down menu or combo box.
Using Only the Index of the Selected Menu Item
This example retrieves only the index of the item selected. It uses a switch statement to take action based on the
value. If the contents of the pop-up menu are fixed, then you can use this approach. Else, you can use the index
to retrieve the actual string for the selected item.
function popupmenu1_Callback(hObject, eventdata, handles)
val = get(hObject,'Value');
switch val
case 1
% User selected the first item
case 2
% User selected the second item
% Proceed with callback...
You can also select a menu item programmatically by setting the pop-up menu Value property to the index of
the desired item. For example,
set(handles.popupmenu1,'Value',2)
selects the second item in the pop-up menu with Tag property popupmenu1.

Button Group
When programming a button group, you do not code callbacks for the individual buttons; instead, use its
SelectionChangeFcn callback to manage responses to selections.
Programming a Button Group
This example of a SelectionChangeFcn callback uses the Tag property of the selected object to choose the
appropriate code to execute. The Tag property of each component is a string that identifies that component and
must be unique in the GUI.

function uibuttongroup1_SelectionChangeFcn(hObject,eventdata)

EGYPTIAN ACADEMY OF
ENGINEERING & ADVANCED
TECHNOLOGY
(EAE&AT)

MATLAB / SIMULINK SUMMER


TRAINING COARSE

Page:118

switch
get(eventdata.NewValue,'Tag') % Get
Tag of selected object.
case 'radiobutton1'
% Code for when radiobutton1 is selected.
case 'radiobutton2'
% Code for when radiobutton2 is selected.
case 'togglebutton1'
% Code for when togglebutton1 is selected.
case 'togglebutton2'
% Code for when togglebutton2 is selected.
% Continue with more cases as necessary.
otherwise
% Code for when there is no match.
end
Plotting to an Axes

1- Add this code to the Plot 1 push button's Callback callback. The surf function
produces a 3-D shaded surface plot. The peaks function returns a square matrix
obtained by translating and scaling Gaussian distributions.
surf(handles.axes1,peaks(35));
2- Add this code to the Plot 2 push button's Callback callback. The contour function
displays the contour plot of a matrix, in this case the output of peaks.
contour(handles.axes2,peaks(35));
3- Run the GUI by selecting Run from the Tools menu.
4- Click the Plot 1 button to display the surf plot in the first axes. Click the Plot 2
button to display the contour plot in the second axes.

EGYPTIAN ACADEMY OF
ENGINEERING & ADVANCED
TECHNOLOGY
(EAE&AT)

MATLAB / SIMULINK SUMMER


TRAINING COARSE

Page:119

Creating Subplots
Use the subplot function to create axes in a tiled pattern. If your GUIDE-generated GUI contains components
other than the subplots, the subplots must be contained in a panel.
As an example, the following code uses the subplot function to create an axes with two subplots in the panel
with Tag property uipanel1. This code is part of the Plot push button Callback callback. Each time you
press the Plot button, the code draws a line in each subplot. a1 and a2 are the handles of the subplots.
a1=subplot(2,1,1,'Parent',handles.uipanel1);
plot(a1,rand(1,10),'r');
a2=subplot(2,1,2,'Parent',handles.uipanel1);
plot(a2,rand(1,10),'b');

EGYPTIAN ACADEMY OF
ENGINEERING & ADVANCED
TECHNOLOGY
(EAE&AT)

get / set

MATLAB / SIMULINK SUMMER


TRAINING COARSE

Page:120

advanced control of all graphics properties. For example, to set the labels on the x axis of
a figure to be cat, dog and rabbit, use:
set(gca,'XTick',1:3,'XTickLabel',{'cat','dog','rabbit'})
gca means get current axis and tells matlab to set the labels on the axis which is currently
active
XTick is the number of tick marks shown on the x axis
XTickLabel is the values attached to each tick mark on the x axis.
Use get(gca) to see all the things which can be set for an axis

Você também pode gostar