You are on page 1of 20

1

Engineering Software Laboratory

PAF-KIET

ENGINEERING SOFTWARE LABORATORY

Lab Manuals | Najeeb Haider Zaidi

Lab No. 2

Engineering Software Laboratory

Lab No. 1

Introduction to Matlab
OBJECTIVE:
To make students familiarized with the Matlab environment, different kinds of operators, Matrices and Array
operations.
THEORY:
1. MATLAB FUNDAMENTALS
MATLAB is numeric computation software for engineering and scientific calculations. The name MATLAB stands
for MATRIX LABORATORY. MATLAB is primarily a tool for matrix computations. It was developed by
John Little and Cleve Moler of MathWorks, Inc. MATLAB was originally written to provide easy access to the
matrix computation software packages LINPACK and EISPACK.
MATLAB is a high-level language whose basic data type is a matrix that does not require dimensioning. There is no
compilation and linking as is done in high-level languages, such as C or FORTRAN. Computer solutions in
MATLAB seem to be much quicker than those of a high-level language such as C or FORTRAN. All computations
are performed in complex-valued double precision arithmetic to guarantee high accuracy.
MATLAB has a rich set of plotting capabilities. The graphics are integrated in MATLAB. Since MATLAB is also a
programming environment, a user can extend the functional capabilities of MATLAB by writing new modules.
MATLAB has a large collection of toolboxes in a variety of domains. Some examples of MATLAB toolboxes are
control system, signal processing, neural network, image processing, and system identification. The toolboxes
consist of functions that can be used to perform computations in a specific domain.
2. MATLAB BASIC OPERATIONS
When MATLAB is invoked, the command window will display the prompt >>. MATLAB is then ready for entering
data or executing commands. To quit MATLAB, type the command
exit or quit
MATLAB has on-line help. To see the list of MATLABs help facility, type
help
The help command followed by a function name is used to obtain information on a specific MATLAB function. For
example, to obtain information on the use of fast Fourier transform function, fft, one can type the command
help fft
The basic data object in MATLAB is a rectangular numerical matrix with real or complex elements. Scalars are
thought of as a 1-by-1 matrix. Vectors are considered as matrices with a row or column. MATLAB has no
dimension statement or type declarations. Storage of data and variables is allocated automatically once the data and
variables are used.
MATLAB statements are normally of the form:
variable = expression
Expressions typed by the user are interpreted and immediately evaluated by the MATLAB system. If a MATLAB
statement ends with a semicolon, MATLAB evaluates the statement but suppresses the display of the results.
MATLAB is also capable of executing a number of commands that are stored in a file.

Engineering Software Laboratory

Lab No. 1

may be entered as follows:


A = [1 2 3; 2 3 4; 3 4 5];
Note that the matrix entries must be surrounded by brackets [ ] with row elements separated by blanks or by
commas. The end of each row, with the exception of the last row, is indicated by a semicolon. A matrix A can also
be entered across three input lines as
A=[123
234
3 4 5];
In this case, the carriage returns replace the semicolons. A row vector B with four elements
B = [ 6 9 12 15 18 ]
can be entered in MATLAB as
B = [6 9 12 15 18];
or
B = [6 , 9,12,15,18]
For readability, it is better to use spaces rather than commas between the elements. The row vector B can be turned
into a column vector by transposition, which is obtained by typing
C = B
The above results in
C=
6
9
12
15
18
Other ways of entering the column vector C are
C = [6
9
12
15
18]
or
C = [6; 9; 12; 15; 18]
To obtain the size of a specific variable, type size ( ). For example, to find the size of matrix A, you can execute the
following command:
size(A)
The result will be a row vector with two entries. The first is the number of rows in A, the second the number of
columns in A.

Engineering Software Laboratory

Lab No. 1

3. MATRIX OPERATIONS
The basic matrix operations are addition(+), subtraction(-), multiplication (*), and conjugate transpose() of
matrices. In addition to the above basic operations, MATLAB has two forms of matrix division: the left inverse
operator \ or the right inverse operator /.
Matrices of the same dimension may be subtracted or added. Thus if E and F are entered in MATLAB as
E = [7 2 3; 4 3 6; 8 1 5];
F = [1 4 2; 6 7 5; 1 9 1];
and
G=E-F
H=E+F
then, matrices G and H will appear on the screen as
G=
6 -2 1
-2 -4 1
7 -8 4
H=
865
10 10 11
9 10 6
A scalar (1-by-1 matrix) may be added to or subtracted from a matrix. In this particular case, the scalar is added to
or subtracted from all the elements of another matrix. For example,
J=H+1
gives
J=
976
11 11 12
10 11 7
Matrix multiplication is defined provided the inner dimensions of the two operands are the same. Thus, if X is an nby-m matrix and Y is i-by-j matrix, X*Y is defined provided m is equal to i. Since E and F are 3-by-3 matrices, the
product
Q = E*F
results as
Q=
22 69 27
28 91 29
19 84 26
Any matrix can be multiplied by a scalar. For example,
2*Q
gives
ans =
44 138 54
56 182 58
38 168 52
Note that if a variable name and the = sign are omitted; a variable name ans is automatically created.

Engineering Software Laboratory

Lab No. 1

Matrix division can either be the left division operator \ or the right division operator /. The right division a/b, for
instance, is algebraically equivalent to

a
b
while the left division a\b is algebraically equivalent to

b
a
.
If

Z*I V and Z is non-singular, the left division, Z\V is equivalent to MATLAB expression
I inv(Z)*V
where inv is the MATLAB function for obtaining the inverse of a matrix. The right division denoted by V/Z is
equivalent to the MATLAB expression

IV*inv(Z)
There are MATLAB functions that can be used to produce special matrices.
Function Description
ones(n,m) Produces n-by-m matrix with all the elements being unity
eye(n) gives n-by-n identity matrix
zeros(n,m) Produces n-by-m matrix of zeros
diag(A) Produce a vector consisting of diagonal of a square matrix A
4. ARRAY OPERATIONS
Array operations refer to element-by-element arithmetic operations. Preceding the linear algebraic matrix
operations, * / \ , by a period (.) indicates an array or element-by-element operation. Thus, the operators .* , .\ , ./,
.^ , represent element-by-element multiplication, left division, right division, and raising to the power, respectively.
For addition and subtraction, the array and matrix operations are the same. Thus, + and .+ can be regarded as an
array or matrix addition.
If A1 and B1 are matrices of the same dimensions, then A1.*B1 denotes an array whose elements are products of the
corresponding elements of A1 and B1.
Thus, if
A1 = [2 7 6
8 9 10];
B1 = [6 4 3
2 3 4];
then
C1 = A1.*B1
results in
C1 =
12 28 18
16 27 40
An array operation for left and right division also involves element-by-element operation. The expressions A1./B1
and A1.\B1 give the quotient of element by element division of matrices A1 and B1. The statement
D1 = A1./B1

Engineering Software Laboratory

Lab No. 1

gives the result


D1 =
0.3333 1.7500 2.0000
4.0000 3.0000 2.5000
and the statement
E1 = A1.\B1
gives
E1 =
3.0000 0.5714 0.5000
0.2500 0.3333 0.4000
The array operation of raising to the power is denoted by .^.
The general statement will be of the form:
q = r1.^s1
If r1 and s1 are matrices of the same dimensions, then the result q is also a matrix of the same dimensions. For
example, if
r1 = [ 7 3 5];
s1 = [ 2 4 3];
then
q1 = r1.^s1
gives the result
q1 =
49 81 125
One of the operands can be scalar. For example,
q2 = r1.^2
q3 = (2).^s1
will give
q2 =
49 9 25
and
q3 =
4 16 8
Note that when one of the operands is scalar, the resulting matrix will have the same dimensions as the matrix
operand.
LAB EXERCISE
Practice the Listed Matrix functions and different operators to get familiarized with the Matlab Environment.
ASSIGNMENT
Create a document stating the general and advance matrix functions available in Matlab.
ASSIGNMENT SUBMISSION DEADLINE
Next Lab session
REFERENCES
Marchand, P., Graphics and GUIs with Matlab, 2nd edition, CRC Press, Boca Raton, FL, 1999.
Hunt, Brian R. Guide to MATLAB : For Beginners and Experienced Users.
West Nyack, NY, USA: Cambridge University Press, 2002.

Lab No. 3

Engineering Software Laboratory

Polynomials and Graphics


OBJECTIVE
To make students familiarized with the solution of the polynomial equations in matlab, generating graphs in matlab
and the special functions related to the tasks.
RELATED THEORY
1. COLON OPERATOR (:)
The colon symbol (:) is one of the most important operators in MATLAB. It can be used (1) to create vectors and
matrices, (2) to specify sub-matrices and vectors, and (3) to perform iterations. The statement
t1 = 1:6
will generate a row vector containing the numbers from 1 to 6 with unit increment. MATLAB produces the result
t1 =
123456
Non-unity, positive or negative increments, may be specified. For example, the statement
t2 = 3:-0.5:1
will result in
t2 =
3.0000 2.5000 2.0000 1.5000 1.0000
The statement
t3 = [(0:2:10);(5:-0.2:4)]
will result in a 2-by-4 matrix
t3 =
0 2.0000 4.0000 6.0000 8.0000 10.0000
5.0000 4.8000 4.6000 4.4000 4.2000 4.0000
2. REPRESENTING A POLYNOMIAL
MATLAB represents polynomials as row vectors containing coefficients ordered by descending powers. For
example, consider the equation. This is the celebrated example Wallis used when he first represented Newton's
method to the French Academy.

To enter this polynomial into MATLAB, use


p = [1 0 -2 -5];
3. POLYNOMIAL FUNCTIONS
The polynomial

is represented in MATLAB as
p = [1 0 -2 -5];
The roots of this polynomial are returned in a column vector by r = roots (p)
r=
2.0946
-1.0473 + 1.1359i
-1.0473 - 1.1359i
Polynomial coefficients from the specified roots can be obtained by using poly() function.
Using the previously found out roots r we can generate a polynomial equation by using the following statement.
poly(r)
It returns,
1.0000
0 -2.0000 -5.0000

Engineering Software Laboratory

Lab No. 3

Polynomial evaluation can be performed at given value of x by using polyval() function.


Evaluation of the p(x) at x=1 can be done using the following statement.
Polyval(p,1)
That results in -6
In order to evaluate a polynomial at multiple values of x, we can use another method, used in the followig example;
p = [3 2 1];
polyval(p,[5 7 9])
which results in
ans =
86 162 262
Now, here, 86 is the evaluated result of the polynomial at x=5, 162 at x=7, and 262 at x=9.
Analytical integration and differentiation of any polynomial can be done by using poltint() and polyder() functions.
4.

POLAR CO-ORDINATES, CARTESIAN CO-ORDINATES INTERCONVERSION

cart2pol() function transform Cartesian coordinates to polar or cylindrical.


[THETA,RHO] = cart2pol(X,Y)
This is the generalized syntax form; THETA is the angle while RHO is the magnitude of the resulting polar vector,
while X and Y are the horizontal and vertical axes co-ordinates of the Cartesian coordinates of the vector.
The command;
[a,b]=cart2pol(2,3)
Results in;
a=
0.9828
b=
3.6056
pol2cart() function transform polar or cylindrical coordinates to Cartesian.
[X,Y] = pol2cart(THETA,RHO)
This is the generalized syntax form; THETA is the angle while RHO is the magnitude of the polar vector, while X
and Y are the resulting horizontal and vertical axes co-ordinates of the Cartesian coordinates of the vector.
The command;
[x,y]=pol2cart(a,b)
Results in;
x=
2
y=
3
5. GENERATING GRAPHS
plot() function generates the Linear 2-D plots. General syntax is as follow
plot(Y) plots the columns of Y versus their index if Y is a real number, If Y is complex, plot(Y) is equivalent to
plot(real(Y),imag(Y))
plot(X1,Y1,...) plots all lines defined by Xn versus Yn pairs. If only Xn or Yn is a matrix, the vector is plotted
versus the rows or columns of the matrix, depending on whether the vector's row or column dimension matches the
matrix
plot(X1,Y1,LineSpec,...) plots all lines defined by the Xn,Yn,LineSpec triples, where LineSpec is a line
specification that determines line type, marker symbol, and color of the plotted lines. You can mix Xn,Yn,LineSpec
triples with Xn,Yn pairs: plot(X1,Y1,X2,Y2,LineSpec,X3,Y3).

Engineering Software Laboratory

Lab No. 3

Following script can be used to generate a sine plot;


t = 0:pi/100:2*pi;
y = sin(t);
plot(t,y)
Following script generates three sine plots with certain phase differences
t = 0:pi/100:2*pi;
y = sin(t);
y2 = sin(t-0.25);
y3 = sin(t-0.5);
plot(t,y,t,y2,t,y3)
You can assign different line styles to each data set by passing line style identifier strings to plot, for example;
t = 0:pi/100:2*pi;
y = sin(t);
y2 = sin(t-0.25);
y3 = sin(t-0.5);
plot(t,y,'-',t,y2,'--',t,y3,':')
see matlab help for lineSpec to customize the line specifications like color, style, markers etc.
polar() function plots polar coordinates. Following are the different syntaxes the function can be used in.
polar(theta,rho) creates a polar coordinate plot of the angle theta versus the radius rho. theta is the angle from the
x-axis to the radius vector specified in radians; rho is the length of the radius vector specified in dataspace units.
polar(theta,rho,LineSpec) LineSpec specifies the line type, plot symbol, and color for the lines drawn in the polar
plot.
Create a simple polar plot using a dashed red line:
t = 0:.01:2*pi;
polar(t,sin(2*t).*cos(2*t),'--r')
LAB EXERCISE
Perform all the examples given in the theory, and check the results.
Write programs to plot the roots of the following polynomial equations on polar chart and on xy plane.

x 4 3x 2 2 x 5 1 0
x2 x3 x0 3
x4 x2 1
LAB ASSIGNMENT
Create a document from the Matlab Help stating the syntaxes and purposes of the different functions in the relation
of polynomial algebra
REFERENCES
Marchand, P., Graphics and GUIs with Matlab, 2nd edition, CRC Press, Boca Raton, FL, 1999.
Hunt, Brian R. Guide to MATLAB : For Beginners and Experienced Users. West Nyack, NY, USA: Cambridge
University Press, 2002.

10

Lab No. 3

Engineering Software Laboratory

Graphical User Interface in Matlab


OBJECTIVE:
To make students familiarized with the Graphical User Interface, designing steps of GUI and its implementation in
Matlab.
RELATED THEORY:
Graphical User Interface:
The Graphical User Interface, or GUI, refers to the now universal idea of icons, buttons, etc., that are visually
presented to a user as a front-end of a software application.
The fundamental power of GUIs is that they provide a means through which individuals can communicate with the
computer without programming commands. The components have become quite standardized and developed into a
user friendly and intuitive set of tools. These tools can be used to increase the productivity of a user or to provide a
window to the sophistication and power of a MATLAB application for people with little or no MATLAB
programming experience.
The components of a GUI in matlab are known as graphics objects and come under two categories; User interface
controls (uicontrols) and user interface menus (uimenus). The uicontrols and uimenus can be combined with other
graphics objects to create informative, intuitive, and aesthetically pleasing GUIs.
Three Phases of GUI Designing:
Analysis:
Before you start your GUI design, you need to consider who will be using it and how. For instance, if you were
creating a computer interface for toddlers, you probably would not use written words, but large, brightly colored
clickable pictures would probably work nicely. However, the same approach would probably not be as well received
if you were tasked with creating an interface for your companys director of marketing (or maybe it would!). The
point is that you need to keep the user in mind. Many MATLAB programmers find themselves as the primary user
of their GUIs. This is because they have found that automating tasks and having a convenient GUI is up-front time
well spent. You might find yourself as part of a development team and your task is to create a rich yet intuitive to
use GUI for functions and data provided by other members. In such a case, the analysis portion of good GUI design
could be very important indeed. The analysis process can become very involved, depending on the goals, and could
require extensive usability specifications, developing user case scenarios, identifying the expertise of the user,
computer system limitations, and plans for future upgrades based on user feedback.
Design:
Once you understand your users and the information that is to be interfaced with, you can begin the process of
laying out your GUI. In the design phase you still arent
writing the GUI, although you might feel like you want to;
instead, you are considering what components, tasks, and
sequences are required to make your GUI effective.
Unbelievably, pencil and paper is still a great way to explore
your GUI design. Again, for major projects, this can become
an involved task, but in the course of the GUI development, it
is time well spent. We will talk about this again in the next
section on Paper Prototyping.
Paper Prototyping:
Perhaps the most effective GUI development process you can
do before actually creating your GUI is to create a paper
prototype. Simply put, take a sheet of paper, and sketch just

11

Engineering Software Laboratory

Lab No. 3

how you want the GUI to appear to the user. Of course, this is done after you have determined what the goals of the
GUI are to be. The paper prototype is a design mockup that lets you explore the layout of your user interface objects,
buttons, dialogs, etc., and data presentation components, e.g., plots. You will be trying to optimize the Position and
organization of your GUI to best accomplish your goal. If your task is large, or if you are part of an organized
software (or analysis) team effort, your paper prototype can also be used to communicate your understanding of the
GUIs goals with the rest of the team.
Design Principles:
Hundreds of books have been written about design, and the best
we can expect to do here is emphasize fundamental themes. The
good news is that the same ideas keep coming up over and over
again. Here is the short list: Simplicity, Consistency, and
Familiarity.
Each word is really the center of a natural group, since many
words can be used to describe the same basic ideas. But of these
concepts, large and small, the undisputed king is this:
Simplicity.
To the quantitatively inclined, these ideals may sound too fuzzy. How can we be more specific? With respect to GUI
design, two metrics inform everything we do:
1 How long does it take to perform a task the first time?
2 How long does it take to perform a task once the interface is familiar?
Each of the themes above bears directly on these two measures.
Simplicity
Emphasize Form, not Number Clutter obscures valuable information. Since visualization is inherently more

qualitative than quantitative, concentrate on the shape and let the labeling vanish.
Minimize the Area of Interaction Dont use two figures when one will do. If youre demonstrating input-output
relationships, put the input right next to the output.
Use Graphical Input Rather Than Numeric Rather than typing in numbers, let the user enter data by directly
touching the graphic. Let the graphic index into itself. Just like in the case of calculator.
Consistency
While using multiple forms/figures, the basic template should be kept constant. Like OK button should remain at the
same position in all the interfaces of the same package.
Familiarity
There are certain standards of a GUI that are preset by the different designers, the customer uses GUI from the
world leaders so, for the comfort of the user, you need to follow those standards, like window sizes, use of tabs in
wizards, and preferring the generic controls rather than designing your own.
Guide
MATLAB is built around a programming language, and as such its really designed with tool-building in mind. uide
extends MATLABs support for rapid coding into the realm of building GUIs.
Guide is a set of MATLAB tools designed to make building GUIs easier and faster. Just as writing math in
MATLAB is much like writing it on paper, building a GUI with Guide is much like drawing one on paper. As a
result, you can lay out a complex graphical tool in minutes. Once your buttons and plots are in place, the Guide
Callback Editor lets you set up the MATLAB code that gets executed when a particular button is pressed.
The five tools that together make up Guide are:
The Property Editor
The Guide Control Panel

12

Engineering Software Laboratory

Lab No. 3

The Callback Editor


The Alignment Tool
The Menu Editor

Guide Environment:
To open GUIDE, select File: New: GUI from the Desktop menu
bar or type guide in the Command Window. You will see the
GUIDE Quick Start dialog box, shown in the Figure.
Note that there are two tabs at the top. The left-hand one, Create
New GUI, is open by default. You can start by selecting one of
the various kinds of GUIs on the left. This will pop open the
Layout Editor, in which you design the appearance
of your GUI.
Lets start from a blank GUI. The layout editor for a blank GUI will
look like the figure. The buttons at the left of the Layout Editor are
used for inserting various kinds of objects. You build a GUI by
clicking on one of these buttons, then moving to a desired location
in the grid, and clicking again to place an object on the grid. To see
what type of object each button corresponds to, move the mouse
over a button but dont click; soon a yellow box with the name of
the button will appear. Once you have placed an object on the grid,
you can click and drag (hold down the left mouse button and move
the mouse) on the middle of the object to move it or click and drag
on a corner to resize the object. After you have placed several
objects, you can select multiple objects by clicking and dragging on
the background grid to enclose them with a rectangle. Then you can
move the objects as a block with the mouse, or align them by
selecting Align Objects... from the Tools menu.
To change properties of an object such as its color, the text within it, etc., you must open the Property Inspector
window. To do so, you can double-click on an object, or choose Property Inspector from the View 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.
UI Controls

13

Engineering Software Laboratory

Above given are the ten common controls for Matlab GUI.
Students are asked to check all of them by pasting on the layout figure one by one.
UI Properties
Every UI Control has certain properties that define its appearance, data type, actions, etc, some common properties
of UI Controls are listed below;

Lab No. 5

14

Engineering Software Laboratory

Lab No. 5

Students are asked to check the effects of each property by changing it on a variety of UI Controls.
UI Callback
Each UI has two components front panel that is actually the user end and the back panel, which is the programmers
domain. Now the User Inputs and Outputs are taken care by the front panel the generation of output on the basis of
inputs takes place the back panel. The basic or you can say crude GUI programming is nothing but changing the
properties of output controls in the reaction of input controls or the value taken input. The rest of the processing is
taken care by nothing but pure general programming. The GUI programming comes under event based
programming category and UI Callback is simply a function that executes when its event takes place. Just like
Button Press on the Push Button. Tag property is the title of Control that programmer use to identify that control
while programming.
While using Guide the basic callbacks can be made quite easily, after creating the layout of your GUI, all you
need to do is to open the M-File Editor from the menu that appears on right click on the figure.
Now this will open a quite huge bulky M-File in the editor, dont get panic, this all is just to define the basic
properties of your UI, which is out of your concern, done by Guide to ease programming pressure from your
shoulders.
Now for an instance, we need to find out the UI callback of PushButton1 (PushButton1 can be the tag of any Push
Button placed on your UI). Scroll the editor downwards until you find the following comment.
% --- Executes on button press in pushbutton1.
Under this comment you will see a function definition and some commented text, now all the statements that you
will type under this function, will execute on button press in pushbutton1. As shown in the figure below; In that
figure the place where you need to type your statements is pointed like, This is the place I was talking about

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

This is the place I was talking about

GUI Programming
The two primary functions of GUI programming that can be used to make an effective GUI are as followed.
Reading the properties of any UI Control.
Changing the properties of any UI Control.
Reading the UI Properties
You can use get() to retrieve the current setting of a property of a graphics object. When you use the callback
templates provided by GUIDE as we have described, the variable hObject will contain the handle for the associated
object.
Syntax
Variable=get(handles.UI-tag, Property Name)
Example
A=get(handle.edit1, string)
Now this will store the value of the string property of the UI tagged edit1 into the variable A.

15

Engineering Software Laboratory

Lab No. 5

Appending the UI Properties


In order to change the property value of any UI control at runtime, all you need to do is to use set() function now as
it seems, for the task to change the value of any property we definitely need three things; UI Control Tag, Property
Name and the value.
Syntax
Set( handles.UI Object-tag, Property Name, value)
Example
Set(handles.edit1, string, abcd)
Well this command will append the string property of UI Control edit1 to abcd now since abcd is a text not a
variable so it will be stated in single quotes.
LAB EXERCISES
1. Draw Calculator GUI.
2. Draw a GUI dialog box consisting of an editable edit box, and two command buttons. Command buttons
should be functioned to increase and decrease the font size of the text of edit box.
3. Draw a GUI dialog box consisting of an editable edit box, and two command buttons. Command buttons
should be functioned to show or hide the text box from the screen. When the edit box is in the figure the
show button should be disabled and when edit box is hidden, the hide button should be disabled.
LAB ASSIGNMENTS
1. Draw a GUI dialog box consisting of an editable edit box, and four command buttons. Command buttons
should be functioned to Move the text box on the screen, upward, downwards, left and right.
2. Draw a GUI with an editable text box and change atleast four properties of the box by atleast four
command buttons.
REFERENCES
Marchand, P., Graphics and GUIs with Matlab, 2nd edition, CRC Press, Boca Raton, FL, 1999.
Hunt, Brian R. Guide to MATLAB : For Beginners and Experienced Users. West Nyack, NY, USA: Cambridge
University Press, 2002.

16

Engineering Software Laboratory

Lab No. 5

Matlab Programming Structures


OBJECTIVE
To familiarize the students with the basic programming structures, their applications in Matlab.
RELATED THEORY

Flow Control
matlab has four kinds of statements you can use to control the flow through your code:
if, else and elseif execute statements based on a logical test.
switch, case and otherwise execute groups of statements based on a logical test.
while and end execute statements an indefinite number of times, based on a logical test.
for and end execute statements a fixed number of times.

If, Else, Elseif


The basic form of an if statement is:
if test
statements
end
The test is an expression that is either 1 (true) or 0 (false). The statements between the if and end statements are
executed if the test is true. If the test is false the statements will be ignored and execution will resume at the line
after the end statement. The test expression can be a vector or matrix, in which case all the elements must be equal
to 1 for the statements to be executed. Further tests can be made using the elseif and else statements.

Switch
The basic form of a switch statement is:
switch test
case result1
statements
case result2
statements
.
.
otherwise
statements
end
The respective statements are executed if the value of test is equal to the respective result s. If none of the cases are
true, the otherwise statements are done. Only the first matching case is carried out. If you want the same statements
to be done for different cases, you can enclose the several result s in curly brackets.
For example,
switch x
case 1
disp(x is 1)
case {2,3,4}
disp(x is 2, 3 or 4)
case 5
disp(x is 5)
otherwise
disp(x is not 1, 2, 3, 4 or 5)
end
For Loop:
For executes statement for a desired number of time. In matlab, unlike in C-Language, we define limit for a variable
and it ends at end keyword. All the statements between for and end statement are executed iteratively.

17

Engineering Software Laboratory

Lab No. 5

For x=a:b:c
Now here x is the variable of the loop a is the starting value of it c is the ending while b is the increment a that will
be done in every iteration.
Example
For x=1:2:10
cPrintf(x=%d\n,x);
end
This program will execute the cprintf statement 5 times.
LAB EXERCISES
1.

2.

Make a program capable of performing following steps.


Take a number; input from the user (let x); should be greater than 0 and lesser than 5.
Take another number input from the user and perform the following set of operations corresponding to the
user input, if it is greater than 6, it should generate error.
1

Sin(x)

Cos(x)

Tan(x)

Cot(x)

x!

x-1

Print the table of the user inputted Number from 1 to 10.

LAB ASSIGNMENTS
1. Study the while loop and create a document explain it functions.
2. Write a Program to make an ordinary calculator of two variables.

18

Engineering Software Laboratory

Lab No. 5

Matlab Simulink
OBJECTIVE
To familiarize the students with the basics of the simulink.
RELATED THEORY
How much time will it take to simulate the output waveform of the following circuit i-e vc(t) if u(t) is unit step.
atleast 15 minutes on paper, well but by using Simulink you can
simulate it quite easily in just 5 minutes. All you need to do is to
replace the circuit by corresponding blocks in simulink. Step supply
from step source, circuit from transfer function and the Scope as the
sink to observe the output.
Now by Laplace transformations the transfer function of this circuit
comes out as follow;

We invoke Simulink from the MATLAB environment, we open a new file by clicking on the blank page icon at the
upper left on the task bar, we name this file Exercise_ 1_ 1, and from the Sources, Continuous, and Commonly Used
Blocks in the Simulink Library Browser, we select and interconnect the desired blocks as shown below.

As we know, the unit step function is undefined at t = 0 . Therefore, we double click on the Step block, and in the
Source Block Parameters window we enter the values shown in the window below.
Next, we double click on the Transfer Fcn block and on the and in the Source Block Parameters window we enter
the values. On the Exercise_ 1_ 1 window, we click on the Start
Simulation icon, and by double-clicking on the Scope block, we
obtain the Scope window shown below.

19

Engineering Software Laboratory

Lab No. 5

While performing this small example you guys might have seen different type of functional blocks and the blocksets
for a variety of applications. Sinks and Sources have different blocksets, Mathematical operations continuous and
discrete functions have different blocksets.
LAB EXERCISE
Perform the Example.
Explore the simulink blocksets.
LAB ASSIGNMENTS
Create a model in simulink, capable of evaluating the derivative of following polynomial functions for
x=sin(w) where 0<w< 2; display their waveforms.

x 4 3x 2 2 x 5 1 0
x2 x3 x0 3
REFERENCES
1. Karris, Steven T. Introduction to Simulink with Engineering Applications.
Fremont, CA, USA: Orchard Publications, 2006. p 45.
2. Matlab Help

20

Engineering Software Laboratory

Lab No. 5

You might also like