Professional Documents
Culture Documents
Faculty of Engineering
Mathematics
February 2013
Lab Notes
MATLAB
Session (1)
MATLAB Notes
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
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
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
a 10
1
A 1
2
x 1 2
3
y 4
5
2 3
0 1
4 5
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
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
Built-in Functions:
sin( )
cos( )
sind( )
cosd( )
asin( )
acos( )
asind( )
acosd( )
cosh( )
sinh( )
asinh( )
acosh( )
eye( ) Identity matrix
tan( )
tand( )
atan( )
atand( )
tanh( )
atanh( )
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
NOTES:
1
A
pi
pi / 2
4
sin(1) sin( pi / 2)
sin( A)
sin(4)
sin( pi)
MATLAB Notes
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
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
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
MATLAB Notes
Type here!
Alexandria University
Faculty of Engineering
Mathematics
March 2013
Lab Notes
MATLAB
Session (2)
Plots Using MATLAB
MATLAB Notes
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
(2,4)
(1,1)
(0,0)
(3,9)
MATLAB Notes
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.
Output Vector
>> x=0:100;
>> 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
is the same as
x=linspace(0,10,12);
gives
x=0:10;
length function:
To find the length (number of points) in a vector use this function.
>> length(x)
MATLAB Notes
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;
>> plot(x,y)
MATLAB Notes
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:
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')
MATLAB Notes
Integral
^
_
\alpha
\pi
\int
\delta
\theta
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:
MATLAB Notes
stem(
o >> x=0:10;
o >> y=x.^3;
o >> stem(x,y)
stairs(
MATLAB Notes
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
>> 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
Line Plot
figure (1.1)
Surface Plot
figure (1.2)
MATLAB Notes
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
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
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
MATLAB Notes
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
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
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.
MATLAB Notes
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
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
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
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
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
After providing
MATLAB with the
height of the surface
at each point this is
how it looks like.
MATLAB Notes
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
MATLAB Notes
1.
2.
3.
4.
Alexandria University
Faculty of Engineering
Mathematics 6
March 2013
Lab Notes
MATLAB
Session (3)
MATLAB Notes
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: )
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.
Oats
Hay')
MATLAB Notes
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
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)
MATLAB Notes
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
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
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
MATLAB Notes
MATLAB Notes
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,
1 n
xi ,
n i 1
Where A is invertible.
MATLAB Notes
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:
MATLAB Notes
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
Snew = Sold + n
n
1
2
3
4
5
Old value of s
0
1
3
6
10
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
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
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
f (Old Value)
1
1
2
6
24
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
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
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
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
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
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
Alexandria University
Faculty of Engineering
Mathematics 6
March 2013
Lab Notes
MATLAB
Simulink and GUI
MATLAB Notes
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
Open New
Model
This is where you will find all the blocks you need to build your system.
MATLAB Notes
MATLAB Notes
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
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
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
If you want to view or use the plot OUTSIDE Simulink, click on the Data
History tab.
7
MATLAB Notes
Once you have done these settings, when you run the model, the variable
ScopeData appears in the workspace:
MATLAB Notes
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
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
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
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
13
MATLAB Notes
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