You are on page 1of 68

Alexandria University

Faculty of Engineering

Mathematics
February 2013

Lab Notes

MATLAB
Session (1)

Eng. Sara Hassan Kamel

MATLAB Notes

By: Eng. Sara Hassan Kamel

Introduction
MATLAB (Matrix Laboratory) is a high performance language for technical
computing.
MATLAB Environment:

Command window
This is where MATLAB
commands are written
and executed

Workspace Tab: (click to view)


This is where the variables are shown

Command History:
All commands previously executed in the
command window appear here.
When typing commands in the command
window you may use the up and
down arrows to navigate through
previous commands and modify them or reexecute them.

MATLAB Notes

By: Eng. Sara Hassan Kamel

MATLAB is case sensitive, that is two variables A and a correspond to


different variables.
Variable names must begin with a letter NOT a number
o e.g.: a
A
a_1 A1
fmax
If you assign a different value to an existing variable, its current value will be
overwritten. If you will need the current value, you must use a new variable to
store your data.
To view a previously written command use the up key and navigate using
up and down keys.
To clear the command window use
>> clc
To clear the workspace use
>> clear all
To close figure windows
>> close all

Scalars, Vectors, Arrays (Matrices) and Dimensioning:


Arrays (Matrices):
An array (or a matrix) is a data unit that consists of many elements. For example, a
4-by-3 matrix consists of 4 rows by 3 columns of numbers:

1
6
A
2

4 5
9 0
3 6

0 9

Vectors:
A vector is a special case of an array; it is an array that consists of either one column
OR one row only.

x 1 3 4 6

Row Vector

2
y 5
8

Column Vector

Scalar:
A scalar is an array of one element only (a 1-by-1 matrix). It can simply be regarded
as a number.

MATLAB Notes

By: Eng. Sara Hassan Kamel

Defining Variables in MATLAB:

a 10
1
A 1
2
x 1 2

3
y 4
5

2 3
0 1
4 5

3 4

To define these variables use the following commands:


>> a=10;
>> A=[1 2 3;1 0 1;-2 4 5];
>> x=[1 2 3 4];

OR

x=[1,2,3,4];

>> y=[3;4;5];
NOTES:

If we remove the semicolon ; from the end of the command line the output
is displayed in the command window:

Use square brackets to define matrices, row vectors and column vectors.
Use a comma , or space to move between elements in the SAME ROW.
Use a semicolon to move to the NEXT ROW.
Variables are saved temporarily in your workspace as shown:

Predefined Constants:
Among the predefined constants in MATLAB are the values of
the value of i

1 written as i or j

written as pi and

MATLAB Notes

By: Eng. Sara Hassan Kamel

Basic Operators:
+
.*
*
./
/
.^
^

Addition
Subtraction
Element-by-element Multiplication
Matrix Multiplication
Element-by-element Division
A/B means AB 1
Element-by-element exponentiation
A^3 means matrix multiplication as follows: AAA

Element-by-Element Multiplication:
Matrices must be of the SAME SIZE
Multiplying A.*B means multiplying every element in A by the corresponding element
in B (i.e. the element in the same location) to produce a matrix of the SAME SIZE as
A and B.
For example:

1 4 5
10 3 4
A
B

1 9 2
3 0 2

1 *10 4 * 3 5 * 4 10 12 20
A *B

3
*
1
0
*
9
2
*
2

3 0 4
Matrix Multiplication:
Matrices must satisfy the following condition The number of columns of the first
matrix must be equal to the number of rows of the second matrix (i.e. their inner
dimensions agree) and the resulting matrix has same number of rows as the first
matrix and the same number of columns as the second matrix.
Meaning that

Amn * Bn p Cm p
For example:

1 2
2 4 2
A
B

1 0 3
2 3

1* 2 2 *1 1* 4 2 * 0 1* 2 2 * 3 4 4 8
A* B

2 * 2 3 *1 2 * 4 3 * 0 2 * 2 3 * 3 7 8 13

MATLAB Notes

By: Eng. Sara Hassan Kamel

Built-in Functions:

sin( )
cos( )
sind( )
cosd( )
asin( )
acos( )
asind( )
acosd( )
cosh( )
sinh( )
asinh( )
acosh( )
eye( ) Identity matrix

sqrt( ) Square Root


exp( ) Exponential
ex
log( ) ln(x)
log10( ) log(x)
real( ) Real part of a complex number
imag( ) Imaginary part of a complex number
abs( ) Magnitude or absolute value
angle( ) Angle of a complex number
max( ) Maximum valued element in a matrix
find( ) gives the indices of the elements that satisfy the argument

tan( )
tand( )
atan( )
atand( )
tanh( )
atanh( )

angle in radians: e.g.: sin()


angle in degrees: e.g.: sind(180)
Output: angle in radians
Output: angle in degrees

The functions mentioned here are only a few of the many functions defined in
MATLAB. You may not use all the function mentioned here during the lab sessions
but they are here for future reference. If you wish to know more about any of these
functions (or a function that is not listed above) you may use MATLAB help.

MATLAB Notes

By: Eng. Sara Hassan Kamel

NOTES:

With scalars, it doesnt matter whether you use matrix or element-by-element


operations.
To add or subtract matrices they must be of the SAME SIZE
To multiply matrices:
Element-by-Element (A .*B): SAME SIZE
Matrix Multiplication (A*B): No. of Columns of A = No. of Rows of B
Applying some built-in function such as sin, cos, tan, exp, to a matrix means
applying the function to every element in the matrix:

1
A
pi

pi / 2
4

sin(1) sin( pi / 2)
sin( A)
sin(4)
sin( pi)

The result of the following commands may confuse you:


o >> sin(0) = 0
o >> sin(pi) = 1.2246e-016
o >> tan(pi/2) = 1.6331e+016
The number 1.2246e-16 means 1.22*10 16 which is a very small number
almost equal to zero which is the result you might expect when executing
sin(pi). Similarly 1.6331e+16 = 1.6331*10 16 is a very large number.
WHY?? Remember that the value of pi is stored in MATLAB is only an
approximation of the actual value .

MATLAB Notes

By: Eng. Sara Hassan Kamel

Matrix Concatenation:
Concatenation means gluing two or more matrices together to create a larger
matrix. There are basically two types of concatenation: horizontal and vertical.
Horizontal Concatenation:
Matrices must have the same number of ROWS.
The resulting matrix has the same number of rows as the original ones and
the number of columns is equal to the sum of the number of columns of the
concatenated matrices.
Vertical Concatenation:
Matrices must have the same number of COLUMNS.
The resulting matrix has the same number of columns as the original ones
and the number of rows is equal to the sum of the number of rows of the
concatenated matrices.

Vertical

Horizontal Concatenation:

Horizontal

Both

MATLAB Notes

By: Eng. Sara Hassan Kamel

Vertical Concatenation:

Both:

Question:
If we have A3x4, B3x2 and C4x6, which of them can be concatenated and how?
Answer:
A and B Horizontal Concatenation [A B]
A and C Vertical Concatenation [A ; C]
A and B horizontally then C vertically [A B ; C]

B
C

MATLAB Notes

By: Eng. Sara Hassan Kamel

Matrix Indexing:
To read a certain element (or multiple elements) within a matrix or vector:
Given:
>> A =
1

-2

>> A(3,2)
6
>> A([1 2],[3 1])
0

-2

>> A(1,:)
1

>> A(8)
-2

In this case MATLAB counts the elements column by column.

>> B=[1 2 8 4];


>> B(2)
8
>> B(end)
4

MATLAB Notes

By: Eng. Sara Hassan Kamel

Getting Help with MATLAB:

There are basically two methods to access MATLAB help:


1. By clicking the Help Button in the MATLAB toolbar as shown:

This will open a new window:

Type here!

Use the search bar to type what youre looking for.


2. Inline Help:
If you know the name of the function youre looking for, for example plot, you can
type the following command in the command window:
>> help plot
This displays a brief explanation of how to use the function and its syntax. To access
the full help document (the reference page in the Help Browser) go to the last line
displayed on the screen and click on doc plot.

Alexandria University
Faculty of Engineering

Mathematics
March 2013

Lab Notes

MATLAB
Session (2)
Plots Using MATLAB

Eng. Sara Hassan Kamel

MATLAB Notes

By: Eng. Sara Hassan Kamel

Two-Dimensional Plots:
In order to plot any line or curve, you need a set of points, namely, the
coordinates (x, y) of each point. Once youve marked these points on the x-y
plane, you join them together. This is the way MATLAB works. You give it the
set of points (data) in the form of two vectors equal in length, then MATLAB
plots the points and joins them together using straight lines.
Example:
Given the following data:
x
0
1
2
y
0
1
4
To plot these we will view them as follows:
x
y

0
0

1
1

2
4

3
9

4
16

3
9

4
16

(0,0) (1,1) (2,4) (3,9) (4,16)

Now we plot the points:


(4,16)
Notice how the points are
joined by straight lines even
though clearly these points
are most likely to represent
the curve y=x2

(2,4)

(1,1)
(0,0)

(3,9)

MATLAB Notes

By: Eng. Sara Hassan Kamel

The simplest way to plot a function is by executing the following commands:


>> x=[0 1 2 3 4];
>> y=[0 1 4 9 16];
>> plot(x, y);

This leads us to the following question: What if we need to plot the function
y=x2 from x=0 to x=100 using 101 points? Here we will use the colon operator
or the built-in function linspace.

The Colon Operator:


Command

Output Vector

>> x=0:100;

Produces a vector of 101 points from 0 to 100


with a unit step (step=1)

>> x=0:2:10;

x = 0 2 4 6 8 10

>> x=0:3:10;

x=0 3 6 9

>> x=10:-1:1;

x = 10 9 8 7 6 5 4 3 2 1

>> x=10:-2:1;

x = 10 8 6 4 2

x = start:step:end;
NOTES:
The default step size is 1. So if no step size is specified as in the first
example then it will be assumed 1.
If you wish to create a sequence of descending numbers use a negative
step. Remember here that you must specify the step size even if its -1
(MATLAB will not assume a step size of -1 if you write a starting number
that is greater than the end of the sequence; instead, youll get an
empty vector.

MATLAB Notes

By: Eng. Sara Hassan Kamel

The linspace function:


This function is used to generate linearly space vectors. Use it when you know
how many points you want in the vector rather than the step (as well as, of
course, the starting and end point of the vector).
linspace(start, end, NumberOfPoints)
Example:
x=linspace(0,10,11);

is the same as

x=linspace(0,10,12);

gives

x=0:10;

0, 0.9091, 1.8182, 2.7273, 3.6364, 4.5455, 5.4545, 6.3636,


7.2727, 8.1818, 9.0909, 10.0000

length function:
To find the length (number of points) in a vector use this function.

>> length(x)

MATLAB Notes

By: Eng. Sara Hassan Kamel

2D Plots:
To plot a function f(x,y) you need to define both x and y.
Example: To plot x+y=1 from x= 5 to x=5
>> x=-5:5;
>> y=1-x;
>> plot(x,y)

To plot y x

>> y=x.^2;

Here we use element-by-element multiplication

>> plot(x,y)

Here the curve is not smooth; thats


because we used x=-5:5 (i.e. with a
step equal to 1) so MATLAB computes
the value of y at (-5,-4, -3.....2,3,4,5)
only and joins them with straight lines.
To get a smoother curve, use a
smaller step:
>> x=-5:0.1:5;

MATLAB Notes

By: Eng. Sara Hassan Kamel

Editing the plot:


You can add a grid, title, labels and legends to the plot. You can also change the
colour of the plot and use markers each point on the plot. You can plot more than
one function in the same figure.
Quick Note: Strings in MATLAB:
A string is a sequence of characters (letters, numbers and/or symbols). In some of
the functions used here you will need to enter a string input such as the title of the
plot. In that case, for MATLAB to recognize your input as a string you need to put it
between single quotation marks. (e.g. 'MATLAB Session (2): First Plot').

plot Function:
2nd Curve

1st Curve

...

plot(x,y,'r--o',x2,y2,'g-*',....)
Line Color

Marker Type

Line Style

NOTES:
To plot several plots on one figure there are two methods:
Use one plot function as indicated above
After the first plot, type >> hold on then type the next plot commands.
When youre done and you dont want the following commands to affect the
previous plot type >> hold off
The following functions take one string input:
o title(
o xlabel(
o ylabel(

)
)
)

The function legend adds a small box at the top right corner of the figure that shows
a sample of each line or curve in the plot described by a text label that you specify.
For example, if you have three curves, you may write:

>> legend('curve 1','curve 2','curve 3')

MATLAB Notes

Example:
>> x=0:10;
>> y1=x.^2;
>> y2=1-exp(-2*x);
>> y3=x;
>> plot(x,y1,'b--',x,y,'r*',x,y3,'g')
>> grid on
>> title('Lab 2')
>> xlabel('x')
>> ylabel('y')
>> legend('y=x^2','y=1-e^-^2^x','y=x')

By: Eng. Sara Hassan Kamel

MATLAB Notes

By: Eng. Sara Hassan Kamel

Using LaTex Interpreter:


To use Greek letters, subscripts, superscripts and style of the text in a string such as
the title we use the LaTex Interpreter tool.
Superscript (e.g. x2)
Subscript (e.g. Pav)

Integral

^
_
\alpha
\pi
\int
\delta
\theta

The full list is available in MATLAB help Text Properties OR Annotation


Textbox Properties.
Markers, Colours & Line Types:
Syntax
r
g
b
k
m
y
c
w

Colour
red
green
blue (default)
black
magenta
yellow
cyan
white

Syntax

-:
-.

Line Type
Solid (default)
Dashed
Dotted
Dash-dotted

Syntax

Marker Type
No Marker (default)
o
Circular
s
Square
p
Pentagonal
h
Hexagonal
d
Diamond
v
Triangular (down)
<
Triangular (left)
>
Triangular (right)
x
Cross
You may also use the following:

hold on To make several superimposed plots with several plot


commands.
xlim([a b]) To limit the x-axis from a to b only.
ylim([a b]) To limit the y-axis from a to b only.

MATLAB Notes

By: Eng. Sara Hassan Kamel

More plotting commands:

fplot(function,limits) function is a string with a variable x


e.g. (sin(x) OR x^2).
o Example:
>> fplot('exp(x)',[-2 2])

stem(

o >> x=0:10;
o >> y=x.^3;
o >> stem(x,y)

stairs(

o >> stairs (x,y)

MATLAB Notes

By: Eng. Sara Hassan Kamel

Subplots:

>> subplot(m,n,p)
It divides the figure into an m-by-n matrix, and plots the figure in the following
command in the pth element, where the elements are counted along the top row then
the second row and so on...
>> subplot(4,1,1)
>> subplot(4,2,3)
>> subplot(4,2,4)
>> subplot(4,4,9)
>> subplot(4,4,10)
>> subplot(4,4,13)
>> subplot(4,4,14)
>> subplot(2,2,4)
After every subplot command write the plotting command for the function you
want to plot in that specified space.

MATLAB Notes

By: Eng. Sara Hassan Kamel

Using the figure command:


Executing the following command opens an empty figure ready for you to plot:

>> figure
This can be useful if you want to plot several functions each in a separate window.
But BE CAREFUL:
If you have several figures open, and you open a new figure to plot, then you go
back and click on one of the previous plots, the new plot command will be executed
in the current or active figure in other words the one you last clicked on!!

Tips:

All vectors used to plot a 2D or a 3D figure must all be of the SAME LENGTH.

If you want to plot a point, use scalars instead of vectors in the plotting
function (e.g. plot(3,5, 'o')). If you want to plot several points, put them
in a vector, and when specifying the line color, type and marker, just write the
color and the marker like this for example: plot(x,y,'ro'). This could also
be useful if you want to use markers of a different color!

You can some properties of the resulting plot by using the plot editor in the figure:
(Click the arrow to start editing).

MATLAB Notes

By: Eng. Sara Hassan Kamel

Three-Dimensional Plots (3D plots):


There are two main types of 3D plots:
1. Line Plots
2. Surface Plots
As you should know, you can draw a line or a curve in a 3-dimensional space
(i.e. with 3 coordinates; x, y and z). You can also draw a plane or a surface. That
is how the types of 3D plots are classified in MATLAB. The following part will
give you more details about how the program deals with each type.

Line Plot
figure (1.1)

Surface Plot
figure (1.2)

MATLAB Notes

By: Eng. Sara Hassan Kamel

3D Line Plots:
As you have already learned in 2D plots, MATLAB plots a set of points given to
the plot function in the form of two equal-length vectors and joins them with
straight lines. Similarly, we deal with line plots as a set of points (this time,
each has 3 coordinates) that we join together by straight lines.
To plot these we will view them as follows:
x
y
z

0
0
0

1
1
1

2
4
2

3
9
3

4
16
4

(0,0,0) (1,1,1) (2,4,2) (3,9,3) (4,16,4)

Now we plot the points using the function plot3 for line plots:

plot3(x,y,z)

plot3(0:4,[0:4].^2,0:4)

OR
(4,16,4)

(3,9,3)

(2,4,2)

(1,1,1)

(0,0,0)

x=0:4;
y=x.^2;
z=x;
plot3(x,y,z)

MATLAB Notes

By: Eng. Sara Hassan Kamel

Parametric Representation:
Say we have a direct relation between the variables x and y:
y=x2
We can use an extra variable - a parameter- to rewrite the equation as:
x=t
y=t2
This is just a simple example, where it may appear that using the direct relation
is much more convenient, but in other cases, the direct relation is more
complicated and using the parametric form is a lot easier.
Example:
We want to plot a helix. A helix is a 3D spiral shape whose equations (in
parametric form) are:
x cos t
y sin t
zt

So we execute the following commands:


t=-10*pi:pi/100:10*pi;
x=cos(t);
y=sin(t);
z=t;
plot3(x,y,z)
grid on

MATLAB Notes

By: Eng. Sara Hassan Kamel

Notice that the function plot3 has the same options as plot, meaning that you
can change the color, line type and marker type as follows:
plot3(x,y,z,'r--o')

This will change the line to a red, dashed line with circular markers. You can
also add a grid, title, legend, x, y and z labels.

Commands:
t=-2*pi:pi/100:2*pi;
x=cos(t);
y=sin(t);
z=t;
plot3(x,y,z,'r--o',z,y,x,'b-*')
grid on
title('Helix')
xlabel('x-axis')
ylabel('y-axis')
zlabel('z-axis')
legend('Helix1','Helix2')

Note: The figure here has been rotated to get a better view of the plots. The default
view may look different when running the commands in MATLAB. Rotation will be
explained later in these notes.

MATLAB Notes

By: Eng. Sara Hassan Kamel

Notice the difference between the following 3D plots of a helix. Look at the
ranges of t in each case.

t=-pi:pi/100:pi;
plot3(cos(t),sin(t),t)

t=-5*pi:pi/100:5*pi;
plot3(cos(t),sin(t),t)

t=-pi:pi/100:pi;
plot3(cos(3*t),sin(3*t),3*t)

t=-5*pi:pi/100:5*pi;
plot3(cos(t/2),sin(t/2),t/2)

MATLAB Notes

By: Eng. Sara Hassan Kamel

Property Editor:
Instead of using functions like title, xlabel and editing the colors of the line
using strings like 'r--o' you can do all this editing using the Property Editor.

Click Edit Figure Properties


This opens the property editor beneath the figure, there you can manually
change the different parts of the figure:
1. The background of the figure (default: grey)
2. The axes background (default: white)
3. The line/curve (default: blue, solid, no marker)

MATLAB Notes

By: Eng. Sara Hassan Kamel

The Figure Background:

Selection

Notice that the background is selected if the black squares appear as in the
figure. Here you can change the grey background from the Figure Color as
indicated.
The Colormap will be used later on in surface plots. However, here in line
plots it has no function.

MATLAB Notes

By: Eng. Sara Hassan Kamel

The Figure Axes:

To select the axes (the yellow part here) click on them. The selection square
markers will show the selected part. Now you can change the color, the grid,
the limits and the labels.

MATLAB Notes

By: Eng. Sara Hassan Kamel

The Line or Curve:

Here you can change the line type, color and thickness as well as the marker
type, facecolor and outline color.
Heres an example: (Zooming in on a modified line):

MATLAB Notes

By: Eng. Sara Hassan Kamel

You can also use Insert and choose any of the options shown.
For some options, like adding or removing the grid, you can right click on the
axes (or the line, whichever part you wish to modify) and do what you want
using the menu that appears.
It is important to note that all these options are available for 2D plots as well.

MATLAB Notes

By: Eng. Sara Hassan Kamel

3D Surface Plots:
In order to draw a surface, you first need to create a grid in the x-y plane, and
then, at every point in this grid, specify the height (z-coordinate) of the surface
by using z as a function of x and y.
Notice that when dealing with lines we use vectors of the same length. We
take the 1st element in x with the 1st element in y and in z to create the 1st
point, then the 2nd element in x, y and z to create the 2nd point and so on
To create a grid we want the 1st element in x with ALL the elements of y, then
the 2nd element of x with ALL the element of y and so on

This is what a grid


looks like.
You dont actually
see this grid, you
visualize it.

After providing
MATLAB with the
height of the surface
at each point this is
how it looks like.

MATLAB Notes

By: Eng. Sara Hassan Kamel

Example:
Plot the function z cos x sin y for x and y ranging from 0 to 10.
Commands:
x=0:0.2:10;
y=x;
[x,y]=meshgrid(x,y);
z=cos(x).*sin(y);
mesh(x,y,z)
figure
surf(x,y,z)
figure
surf(x,y,z)
shading interp

This command creates the grid i.e.


instead of having two vectors x and y
(each 1x51) we get two matrices (51x51).
Look at the workspace before and after
executing this to see the difference.

mesh(x,y,z) plots a wireframe


surface.
Notice that the gridlines of the surface are
colored while the spaces (or squares) in
between are white.
The highest points on the surface are red
while the lowest points are dark blue.

surf(x,y,z) plots a continuous,


colored surface.
Notice that the gridlines of the surface are
black while the spaces in between are
colored according to the height of the
surface points.

MATLAB Notes

By: Eng. Sara Hassan Kamel

Executing the command:


>> shading interp
After plotting using surf removes
the black gridlines and creates a
smooth colored surface.
This command, however, has no
effect on mesh plots.

Additional options for 3D surface plots in the Plot Editor:


Colormap: Changes the gradient colors of the surface and mesh plots.

Rotate: (Works for all 3D line and surface plots)

1.
2.
3.
4.

Click the Rotate 3D button.


Go to the plot in the figure.
Click and drag to rotate.
If you wish to return to the original view, right click (with the rotation
cursor active) and choose Reset to Original View.

Alexandria University
Faculty of Engineering

Mathematics 6
March 2013

Lab Notes

MATLAB
Session (3)

Eng. Sara Hassan Kamel

MATLAB Notes

By: Eng. Sara Hassan Kamel

Using input and disp functions


Input Function (input):
user_entry = input('prompt')
user_entry = input('prompt', 's')

Use input function when you want to ask the user to enter a certain value
then you can save it in a certain variable.
Example:
>> x = input(Enter the value of x: )

The previous command displays the following in the command window:


Enter the value of x:

Now the user should type in the value of x, say 10. So type 10 and click enter.
This way the value 10 is assigned to the variable x and it appears in the
workspace.
Example:
>> word = input(Enter password: , s)

The previous command has an extra input s which means that whatever the
user types in will be treated as a string not a numerical value. So if you type in
lab3 then lab3 will be treated as a string and stored in the variable word.

Display Function (disp):


Use this function to display a certain string or array to the user in the
command window. Here whatever you type in as an input to the function
disp will not be stored anywhere, it will just be displayed.
Example:
>> disp('
Corn
>> disp(rand(5,3))

Oats

Hay')

MATLAB Notes

By: Eng. Sara Hassan Kamel

Results in:
Corn
0.2113
0.0820
0.7599
0.0087
0.8096

Oats
0.8474
0.4524
0.8075
0.4832
0.6135

Hay
0.2749
0.8807
0.6538
0.4899
0.7741

MATLAB m-files:

NEW m-file
Instead of writing commands and executing them one by one in the command
window we can create a file, write all commands and then run the file. There
are two types of m-files:
SCRIPTS:
No inputs or outputs defined
Consist of a sequence of instructions
You can choose any filename to save the script
FUNCTIONS:
Can have inputs and outputs
Must start with the following line:
function [op1,op2,...]=function_name(ip1,ip2,....)

The filename must be the same as the name specified in the previous
(first) line i.e. in this example it should be function_name.m

MATLAB Notes

By: Eng. Sara Hassan Kamel

Note that both scripts and functions have the extension .m, but the content
of each type is different as mentioned earlier.
Example:
Write a function and a script that count the number of elements of a given
matrix. Test your program for the matrix:
1
4

1
2

2
5
0
0

3
6
0
4

Now to do that you can use the function numel( )which directly gives the
number of elements in the given matrix. Another solution would be to use the
function size which had 2 outputs: the number of rows and the number of
columns, then multiply the two results.
SCRIPT:
A=input('Enter the input matrix: ');
x=numel(A);
disp(['The number of elements in the given matrix is ', num2str(x)])

Or use this:
disp('The number of elements in the given matrix is:')
disp(x)

Where the function num2str converts x from a numerical value to a string.


We use this function because the input to disp must be only one input; either
a string or a numerical value/array. So we construct a vector whose elements
are all strings, the first part is the string The of elements in the given matrix is
and the other is the number in x converted to string.
To run the script and execute the commands in the script, there are two ways:
1. Type the filename in the command window and click enter
>> lab3_script1
2. Click the Run button at the top of the m-file window:

MATLAB Notes

By: Eng. Sara Hassan Kamel

FUNCTION:
Here we shall try using size instead of numel
function [x]=lab3_fn1(A)
[r c]=size(A);
x=r*c;

Now the function lab3_fn1 can be used the exact same way you use numel
or any other built-in function, as long as the function is saved in your current
directory.
>> B=[1 2 3;4 5 6;1 0 0;2 0 4]
B =
1
4
1
2

2
5
0
0

>> numel(B)
ans =
12
>> lab3_fn1(B)
ans =
12

3
6
0
4

MATLAB Notes

By: Eng. Sara Hassan Kamel

Write a function that replaces a specific column of a given matrix by some


other column vector. Test your program on the matrix in the previous problem.
Try replacing the second column by the vector
v = [ 1 1 0 0]t.
function [A_new]=lab3_fn2(A,x,n_col)
A_new=A;
A_new(:,n_col)=x;
The last line means that we replace all rows in the column number n_col in
the matrix A by the vector x (which must be a column vector whose size is
suitable for this replacement to occur.
>> lab3_fn2(B,[1;1;0;0],2)
ans =
1
4
1
2

1
1
0
0

3
6
0
4

Write a script file that takes as input a matrix and displays a menu of
elementary row operations (interchanging rows, addition of a multiple of a row
to another, multiplying a row by a non-zero constant) together with an exit
option. Display the resulting matrix after performing the desired row
operation.
We will use the switch function:
Syntax:
switch variable
case value1
....
case value2
....
:
:
otherwise
....
end

MATLAB Notes

By: Eng. Sara Hassan Kamel

ANSWER:
A=input('Enter the matrix: ');
disp('Which of these row operations do you want to execute?')
disp('(1)Interchanging Rows')
disp('(2)Multiplying a row by a Scalar')
disp('(3)Adding Two Rows')
x1=input('Enter 1,2 or 3 for the required row operation: ');
switch x1
case 1
disp('Which rows do you want to interchange?')
r1=input('Number of 1st row: ');
r2=input('Number of 2nd row: ');
temp=A(r1,:);
A(r1,:)=A(r2,:);
A(r2,:)=temp;
disp(A)
case 2
c=input('Scalar: ');
r=input('Number of row: ');
x=c*A(r,:);
A(r,:)=x;
disp(A)
case 3
r1=input('First row: ');
r2=input('Second row (in which the addition operation
is executed: ');
x=A(r1,:)+A(r2,:);
A(r2,:)=x;
disp(A)
end

Write a function to plot a circle. (Hint: use the parametric representation of


the circle).
A circle of radius a is written in parametric form as:
X=a*cos(t)
Y=a*sin(t)
NOTE:
A function may not have numerical outputs, such as this one, so we omit the
output part from the first line and we just write
function fn_name(ip1,..)

MATLAB Notes

By: Eng. Sara Hassan Kamel

So the function will be written as follows:


function plotcircle(r)
t=0:0.01:2*pi;
x=r*cos(t);
y=r*sin(t);
plot(x,y)
axis square

This makes the y-axis


appear the same length
as the x-axis so the
circle doesnt appear
oval.

Write a script and a function according to the description:


1) Write a program to plot the function Acos(wt). The user should be able to
specify the amplitude A, the frequency w, the range of t (starting point, end
point and step size separately) as well as the line color, type and marker
type.
Solution:
Script:
ts=input('Enter the starting point of the range: ');
tf=input('Enter the end point of the range: ');
tstep=input('Enter the step: ');
A=input('Enter the Amplitude of the Sine Wave: ');
w=input('Enter the value of w in Acos(wt): ');
spec=input('Specify the line color, type and marker: ','s');
t=ts:tstep:tf;
x=A*sin(w*t);
plot(t,x,spec)
title('Sine Function')
xlabel('x')
ylabel('y')
grid on

MATLAB Notes

By: Eng. Sara Hassan Kamel

Function: (the filename is plot2Dsin.m)


function plot2Dsin(ts,tf,tstep,A,w,spec)
t=ts:tstep:tf;
x=A*sin(w*t);
plot(t,x,spec)
title('Sine Function')
xlabel('x')
ylabel('y')
grid on

Exercises:
1- Write a function that solves a 3 3 system of linear equations using
Cramers rule. Your program should test whether the input matrix is
singular in which case displays an error message. Make use of the
function you created in problem 2. Test your program using the
following system of linear equations:
x y + z = 3,
x + 3y + z = 1,
x 3z = 2.
2- Write a function that computes the mean, variance and standard
deviation of a given set of data points. Test your program using the
following data set: x1 90, x 2 75, x 3 93, x 4 69 . Display helpful
messages. Compare your results with those obtained using the
corresponding MATLAB built-in functions. (Hint: the estimates for the
mean,

variance and standard deviation are given by m

1 n
xi ,
n i 1

v ( x i m) 2 /(n 1) and s v , respectively)


i 1

HINT: Cramers Rule:


Consider a system of linear equations represented in matrix multiplication
form as follows:
Ax=b

Where A is invertible.

Then the theorem states that:

MATLAB Notes

By: Eng. Sara Hassan Kamel

where Ai is the matrix formed by replacing the ith column of A by the column
vector b.
Example:
2x + y + z = 3
xyz=0
x + 2y + z = 0
Coefficient Matrix is D:

Evaluating each determinant, we get:

Cramer's Rule says that x = Dx D, y = Dy D, and z = Dz D. That is:


x = 3/3 = 1, y = 6/3 = 2, and z = 9/3 = 3

MATLAB Notes

By: Eng. Sara Hassan Kamel

PART (II)
Introduction:
In this session, you will learn how to use some programming functions in
MATLAB. These functions include for, if, switch and others. Such
functions are best explained through examples. This session focuses on for.

for:
Use for to create a loop, i.e. when you want a certain command or a set of
commands to be executed several times.
for variable = initval:step:endval
statement
...
statement
end
Where the variable is the counter, you can give it any name, its just a
variable. For-loops are best explained through examples.
Example (1):
Use a for-loop to sum the numbers from 1 to 5.
Answer:
s=0;
for n=1:5
s=s+n;
end
disp(s)
Now we shall explain how this works:
The idea is to create a variable, give it an initial value and use the loop to add
the numbers inside this variable one by one:

MATLAB Notes

By: Eng. Sara Hassan Kamel

Snew = Sold + n
n
1
2
3
4
5

Old value of s
0
1
3
6
10

New value of s (s=s+n)


1+0=1
2+1=3
3+3=6
4+6=10
5+10=15

Notice that n is a vector (1:5 = [1 2 3 4 5]) so when we enter the loop for the
first time, n takes the value of the first element, and so n=1.
In the second iteration (step), n takes the following elements value - which is 2
- and so on (see the table above).

Example (2):
Write a program (script) to sum up the first 10 even numbers (excluding zero).
Answer:
s=0;
for n=0:2:20
s=s+n;
end
disp(s)
OR
s=0;
for n=1:10
s=s+2*n;
end
disp(s)
Both solutions are correct. However, if you dont know that the first 20 even
numbers are from 2 to 20 (like for example if the question asked you to sum up

MATLAB Notes

By: Eng. Sara Hassan Kamel

the first 57 or 396 even numbers!), then the second solution is the more
appropriate one.
For the second solution:

Snew = Sold + 2n
n
1
2
3
4
5
6
7
8
9
10

Old value of s
0
2
6
12
20
30
42
56
72
90

New value of s (s=s+2n)


2*1+0=2
2*2+2=6
2*3+6=12
2*4+12=20
2*5+20=30
2*6+30=42
2*7+42=56
2*8+56=72
2*9+72=90
2*10+90=110

Note that each time we add an even number; because when n takes the values
1, 2, 3, 4 10, 2n takes the values 2, 4, 6, 8 ...20.

Example (3):
Write a function m-file to calculate the factorial of a given integer. Use the
function name fact.
Answer:
function f=fact(n)
f=1;
for i=1:n
f=f*i;
end
e.g.: The factorial of 5 5! = 5 x 4 x 3 x 2 x 1 = 1 x 2 x 3 x 4 x 5
In general n!= n(n-1)(n-2) 1

MATLAB Notes

By: Eng. Sara Hassan Kamel

Here we initialize f to 1, because any number multiplied by 1 stays as it is.


The loop here keeps the result in f, each iteration it multiplies the previous
value of f to the following integer in the sequence from 1 to n:
To try out the function, do not click Run. Instead you go to the command
window and try the function for any value of n say 5:
>> fact(5)
n
1
2
3
4
5

f (Old Value)
1
1
2
6
24

f (New Value) f=f*n


1*1=1
1*2=2
2*3=6
6*4=24
24*5=120

The result:
ans = 120
>> fact(0)
In this case we have f=1, then in the loop n=1:0 (so this means a vector whose
starting point is 1 and end point is 0 with a step equal to 1, and 1+1=2 > 0.
Hence n is an empty matrix) and the for-loop is not executed at all, therefore f
remains 1.
ans =1
Indeed: 0!=1

MATLAB Notes

By: Eng. Sara Hassan Kamel

NOTE:
MATLAB actually has built-in functions to do some of the examples introduced
here, but still the examples show you how to create a for-loop and trace the
code.
sum(x) This function sums up the elements of x
factorial(x) This function computes the factorial

Example (3):
Create the vector *1 2 4 8 16 . 128+
Answer:
A=[];
for i=0:7
A=[A 2^i];
end
disp(A)
This is what we do:
1. First we create an empty matrix A (or else when we reach the step inside
the loop A will be undefined).
2. A=[A 2^i] will concatenate the new A and the old A to create the vector
step by step.
To see how it works, well remove the semicolon and display the value of i:
A=[];
for i=0:7
disp('i=')
disp(i)
A=[A 2^i]
end

MATLAB Notes

By: Eng. Sara Hassan Kamel

Output:
i=
0
A =
1
i=
1
A =
1

i=
2
A =
1

16

16

32

16

32

64

16

32

64

i=
3
A =
1
i=
4
A =
1
i=
5
A =
1
i=
6
A =
1
i=
7
A =
1

128

MATLAB Notes

By: Eng. Sara Hassan Kamel

Example (4):
Write a script to create a 9x8 matrix whose rows are the same as the vector A
in example (3). Youll need to regenerate A, dont use a previously created
vector.
Answer:
Here we will use two for loops, one inside the other:
A=[];
for i=1:9
B=[];
for j=0:7
B=[B 2^j];
end
A=[A;B];
end
disp(A)
1. First we initialize A as an empty matrix.
2. The first loop repeats 9 times, once for each row.
3. The code within the outer loop is the same as the one in example (3),
including initializing the matrix B as an empty matrix to make it ready for
concatenation.
4. After the inner loop is finished, matrix B contains the vector [ 1 2 4
128+ and is vertically concatenated with A (which starts out as an
empty matrix, then one row, then two and so on)
5. The last line displays the matrix A
Note: This example is for you to learn how to trace two loops one embedded
inside the other. However, you can create the vector *1 2 4 128+ and then
use it in one loop to create the matrix. This way youll use two separate loops.
B=[];
for j=0:7
B=[B 2^j];
end
A=[];
for i=1:9
A=[A;B];
end
disp(A)

MATLAB Notes

By: Eng. Sara Hassan Kamel

Example (5):
Suppose you want to create a script that enables a user who does not know
how to write a matrix using MATLAB to do so by prompting the user to enter
the elements one-by-one. Also, the user should be able to decide the size of
the matrix.
Answer:
m=input('Enter the number of rows: ');
n=input('Enter the number of columns: ');
A=[];
for i=1:m
for j=1:n
x=input('Enter the element: ');
A(i,j)=x;
end
end
disp(A)

First, we ask the user for the number of rows and columns, and we use these in
the loops:
The outer loops is for the rows and the inner one for the columns
The total number of iterations (number of times the commands inside the
inner loop is repeated) is the product of m and n:
For example: if m=3 and n=5: Total number of iterations = 3x5 = 15
i=1
j=1
j=2
j=3
j=4
j=5
i=2
j=1
j=2
j=3
j=4
j=5
i=3
j=1
j=2
j=3
j=4
j=5

MATLAB Notes

By: Eng. Sara Hassan Kamel

This fills up the matrix A row by row:


A(1,1) =
A(1,2) =
A(1,3) =
and so on

Example (6):
Write a script using a for-loop to produce the following plot where the
functions drawn are sin(x), sin(2x), sin(3x) and sin(4x):

x=0:0.1:10;
for n=1:4
subplot(2,2,n)
plot(x,sin(n*x))
end

Do not forget to define x before the loop (if its inside, it


doesnt matter but theres no use repeating it every iteration if
its the same in all plots).

Alexandria University
Faculty of Engineering

Mathematics 6
March 2013

Lab Notes

MATLAB
Simulink and GUI

Eng. Sara Hassan Kamel

MATLAB Notes

By: Eng. Sara Hassan Kamel

I. Simulink
Simulink is a graphical extension to MATLAB for modeling and simulation of
systems. With Simulink, you can build a model for any system and simulate it
using a block diagram.
To open Simulink, click on the indicated icon and wait for the toolboxes to
load:
Simulink Icon

The Simulink Library will open:

Open New
Model

This is where you will find all the blocks you need to build your system.

MATLAB Notes

By: Eng. Sara Hassan Kamel

Basically, to simulate a system using Simulink, you need to do the following


steps:
1. Open a new Simulink Model
2. Drag and drop blocks from the Simulink library into the model
3. Adjust the attributes of the blocks
4. Connect the blocks (CTRL + click)
5. Run
Simulink Library:
The library has some basic toolboxes and other specialized toolboxes or
blocksets (like Power systems, communications, image processing,
Aerospace etc.)
For starters, take a look at the following blocksets:
1) Sources: This one contains signal sources which you can use as inputs to
your system; a sine wave, a unit step function, square pulses.
2) Sinks: Contains different blocks to view the output. You can use a scope
(which looks like the screen of an oscilloscope) or a display (if the output is just
a number not a signal). You can also you To Workspace or simout to
transfer the output value to the workspace as a variable.
The figure below shows the available sinks:

3) Commonly Used Blocks: This is a useful blockset that contains a collection of


some of the most important basic blocks, including some sinks, sources and
mathematical operators.
3

MATLAB Notes

By: Eng. Sara Hassan Kamel

Example:
We start with this simple model as an example of how to use Simulink:

This is where
you click to
RUN the model

Drag and drop the shown 4 blocks from the Simulink library to the new model.
Sine Wave From Sources
Derivative From Continuous
Gain From Commonly Used Blocks OR Math Operations
Scope From Sinks
To connect the blocks you can drag a line from each block to the following one
or click on the first block, press CTRL and click on the other block.

When the mouse pointer turns to a Plus sign (+) you can start dragging.
After connecting the blocks, the model looks like this:

MATLAB Notes

By: Eng. Sara Hassan Kamel

To change the parameters of each block, there are two methods you need to
know:
1. Manually, by double-clicking on the block and changing them.
2. Using an m-file to control the blocks with MATLAB commands.
The manual method is easy and straightforward, for example, this is what you
get when clicking on the Sine Wave block:

If youre using a new block and dont know how to change the parameters,
click on the HELP button (next to OK and Cancel).

MATLAB Notes

By: Eng. Sara Hassan Kamel

Using an m-file to change the block parameters (attributes):


First, you need to save the model. Having done that, open a new m-file (script)
and use the following functions:

set_param(Name of File/Name of Block, Name of attribute, Value)


The function set_param changes the value of a certain parameter. For
example, to change the amplitude of the sine wave to 2 and the gain factor to
0.5 use the following commands (assume the model name is mysim1):
set_param('mysim1/Sine Wave','Amplitude','2');
set_param('mysim1/Gain','Gain','0.5');

If you want to run the model using the m-file (instead of clicking the
you can use the following command:

button)

sim('mysim1')

NOTE: When you run the file, nothing appears! But this is normal. You need
to double click on the scope in order to view the output after running the
model.

MATLAB Notes

By: Eng. Sara Hassan Kamel

Using the SCOPE:


By double clicking on the scope, the output signal will appear in yellow on a
black background. If the output doesnt fit the window, right click on the figure
and click Autoscale.

This button takes


you to the scope
parameters

If you want to view or use the plot OUTSIDE Simulink, click on the Data
History tab.
7

MATLAB Notes

By: Eng. Sara Hassan Kamel

Make sure this is


unchecked

Make sure that


Save Data to
Workspace is
checked.

The variable name is the name of the variable


that shall appear in the workspace, it should
have two columns, one containing the x-values
and the second containing the y-values.
The format should be Array (in order to have
the data in matrix from).

Once you have done these settings, when you run the model, the variable
ScopeData appears in the workspace:

MATLAB Notes

By: Eng. Sara Hassan Kamel

This is an example of an m-file to control and run the model. The script also
plots the output using data from the scope:
set_param('mysim1/Sine Wave','Amplitude','3');
set_param('mysim1/Gain','Gain','2');
sim('mysim1')
x=ScopeData(:,1);
y=ScopeData(:,2);
plot(x,y)
Output:

NOTES:
You can search for blocks in the Simulink Library by typing their name in
the search bar.
You can resize, recolor and rename the blocks in the Simulink model as
well as the background. Right click on any of the blocks to view the
options.
You can rotate any block by selecting it and clicking CTRL+R

MATLAB Notes

By: Eng. Sara Hassan Kamel

II. Graphical User Interface (GUI) using MATLAB


GUIDE: Graphical User Interface Development Environment

GUIDE Icon

By clicking on the indicated icon, you can access the GUIDE. Use the GUIDE to
create a user-friendly interface, like this for example:

Heres how to get started: When you click the icon, this appears. Click OK.

10

MATLAB Notes

By: Eng. Sara Hassan Kamel

Access the GUI


m-file

Run the GUI

This is where you will


create the interface

These are the elements you can add to your


interface; buttons, axes, edit boxesetc.

Example:
The following GUI can plot a variety of functions. You can choose the function
from a drop-down menu. The range of the horizontal axis can be adjusted
using the edit boxes. The radio buttons allow you to choose the color of the
plot (blue or red). The checkbox applies a grid to the figure if checked.
To plot, click the plot button. To clear the figure, click the clear button.
If you want to edit the name or text in any of the GUI elements, double click
the element. The Property Inspector appears. Go to the String option and
type whatever you want. For the drop-down menu, a new line represents a
new selection.
It is preferable to leave the edit boxes blank. The default text is Edit Text.
So go to the property inspector and delete the words Edit Text and leave the
string blank. You could also put a default value if you want.
11

MATLAB Notes

By: Eng. Sara Hassan Kamel

IMPORTANT: Every element (button, box, menu) has a Tag listed in the
property inspector. This is the name you will use later to call the element in the
m-file. You can use the default name, or you can rename it to make it easier for
you to remember what the button does when you are writing the m-file that
controls your GUI.
For example, the default tags for the radio buttons are radiobutton1 for the
Red button, and radiobutton2 for the Blue button. You can rename them
redbutton and bluebutton.

12

MATLAB Notes

By: Eng. Sara Hassan Kamel

Now to the important part: Programming your GUI:


1. Save the GUI figure.
2. Once you save it, an m-file appears. If you want to access this m-file later
you can click on the m-file editor button in the figure.
3. The m-file already has lines of code written. DO NOT ERASE THEM!
4. Each GUI element has a section in which you can write your own
commands. For example, if you want to tell the m-file what to do if the
PLOT button is pressed, go to the line that starts with:
function pushbutton1_Callback(hObject, eventdata, handles)

Now take a look at how the final m-file:


These are the parts of the m-file that were modified:
% --- Executes on button press in checkbox1.
function checkbox1_Callback(hObject, eventdata, handles)
% hObject
handle to checkbox1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles
structure with handles and user data (see GUIDATA)
s=get(handles.checkbox1,'value');
axes(handles.axes1);
if s==1
grid on
else
grid off
end
% --- Executes on button press in pushbutton1.
function pushbutton1_Callback(hObject, eventdata, handles)
axes(handles.axes1);
x0=str2num(get(handles.edit1,'string'));
xf=str2num(get(handles.edit2,'string'));
x=x0:0.01:xf;
ch1=get(handles.popupmenu1,'value');
switch ch1
case 1
y=sin(x);
case 2
y=cos(x);
case 3
y=exp(x);
case 4
y=log(x);
end
ch2=get(handles.radiobutton1,'value');
if ch2==1
color='r';
else
color='b';
end
plot(x,y,color)

13

MATLAB Notes

By: Eng. Sara Hassan Kamel

% --- Executes on button press in pushbutton2.


function pushbutton2_Callback(hObject, eventdata, handles)
% hObject
handle to pushbutton2 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles
structure with handles and user data (see GUIDATA)
cla
set(handles.edit1,'string','');
set(handles.edit2,'string','');
set(handles.popupmenu1,'value',1);
set(handles.checkbox1,'value',0);
set(handles.radiobutton1,'value',1);
set(handles.radiobutton2,'value',0);
axes(handles.axes1);
grid off

As you can see, the only buttons that need modifications in the m-file are the
PLOT, CLEAR and Grid on/off buttons.
More about the functions used:
set To change or set the value of an element (on/off, change the textetc.)
get To get the data entered by the user from the GUI (checked/unchecked,
text, which selectionetc.)
cla Clear Axes
axes To call the axes; you need to use this before you plot.
If you have more than one plotting regions, you need this to specify
which one the program should use.
str2num Converts a string to a number. The opposite is num2str.

To run the GUI, click the Run button in the GUI figure,
NOT the m-file!
Also, if you want to open the figure again anytime, you must do so using the
GUIDE and clicking the Existing GUI tab then searching for your file from
there, not just double clicking the figure file.
One final note: If you want to send the GUI or transfer it from one place to
another, you must send or transfer BOTH the figure AND the m-file.

14

You might also like