Sie sind auf Seite 1von 122

IQRA Software Technologies Pvt. Ltd.

(S/W Development & Training Division)


#117/64, ‘O’ Block, Geeta Nagar, Rawatpur Kanpur-208 025
Phone: 0512-2505298, www.iqrasoftwares.com

IQRA Software All RIGHTS RESERVED 1


Copyright

All rights reserved. No part of this publication


may be reproduced, stored in a retrieval
system, or transmitted, in any form or by any
means, electronic, mechanical, photocopying
or otherwise.

IQRA Software reserves all right to change,


append and redesign, at any given instance,
with without prior notice. Any enquiries
regarding this publication should be directed to
the Rights department of IQRA Software.

********

IQRA Software All RIGHTS RESERVED 2


Table of Contents

1. Introduction To MATLAB.......................................................................... 4
2. MATLAB Computation ............................................................................. 8
3. Programming in MATLAB ...................................................................... 20
4. MATLAB Data Types ............................................................................. 40
5. MATLAB Graphics ................................................................................. 47
6. MATLAB Applications ............................................................................ 58
7. Lab Manual ........................................................................................... 65

IQRA Software All RIGHTS RESERVED 3


Introduction To MATLAB

MATLAB is a high-performance, technical language for mathematical computation and visualization. It


provides an interactive environment with lots of built-in functions for technical computation, graphics and
animations. MATLAB programming is an easy-to-use and very much user friendly. It also provides easy
extensibility with its own high level programming language. MATLAB is a program which allows you to solve
a various number of problems in science and mathematics both numerically and through visualization.
Basically the name MATLAB stands for Matrix + Laboratory.
The basic building block of MATLAB is matrix and the fundamental data type is array.
MATLAB was originally written to provide easy access to matrix software developed by the LINPACK and
EISPACK projects, (sponsored by NASA) which together represent the state-of-the-art in software for matrix
computation.
In university environments, MATLAB is the standard instructional tool for introductory and advanced courses
in mathematics, engineering, and science. In industry, MATLAB is the tool of choice for high productivity
research, development, and analysis.
In industry, MATLAB is the tool of choice for high productivity research, development, and analysis.
MATLAB is used for:
• Simple calculations.
• Easy way to write a program using script files, functions etc.
• Plotting and analyzing mathematical relationships (2- Dimensional and 3- Dimensional).
• Symbolic manipulation of equations.
• Matrix Operations to solve the problems.
• Advanced visualization and GUI interfacing tool.
• Modeling, simulation and prototyping.
The advantages of using MATLAB are as follows:
• Very much flexibility to solve a large number of problems.
• Independent of computer systems and OS.
• The scripting language is relatively easy to learn as compared to other programming language like
COBOL, FORTRAN, C, C++ etc.
• It is used in many disciplines like science, math, computer science, Aerospace, Signal processing,
finance etc.

Is MATLAB software platform dependent?

The most likely answer is “No”. MATLAB supports almost every platform. In addition to PCs and Macintosh
computers, versions are available for SUN SPARCstations, HP 9000 PA-RISC, IBM RS/6000, SG164
workstations and many others.

IQRA Software All RIGHTS RESERVED 4


The basics of MATLAB

Here we will discuss the basic features of MATLAB and commands. Let us look at the general structure of
the MATLAB environment.

MATLAB windows: On all UNIX, WINDOWS systems, MATLAB works through three basic windows.
• Command Window: This is the main window, which is characterized by the MATLAB command
prompt “>>”. When you open the application, you will be able to see this window. You can write all
the commands and functions in this window.

• Graphics Window: The output of all graphics command typed in the command window is
displayed to the graphics or figure window. You can create as many figure windows as the system
memory allow.

IQRA Software All RIGHTS RESERVED 5


• Edit Window: This is the place, where you write, edit, create, and save your own programs in files
called “M-files”. You can use any text editor to carry out these tasks. On almost all operating
systems, MATLAB provides its own built in editor.

Classification of MATLAB system:

The MATLAB system consists of six main parts:

1) Integrated Development Environment: IDE includes the MATLAB desktop and Command
Window, a command history, an editor and a debugger, and browsers for viewing help, the
workspace and the search path. Basically it is a set of tools that help MATLAB programmers to use
functions and files.
When you start MATLAB, you see the MATLAB Desktop, which contains several windows; the
most important of them is the MATLAB Command Window.
When you work with MATLAB, you will define various variables and objects. All these variables and
objects are saved in the MATLAB Workspace. The Workspace browser can be found in the upper
left-hand corner.
2) Handle Graphics: MATLAB provides high level of commands for two-dimensional and three-
dimensional data visualization, image processing and presentation graphics. MATLAB, an
Interactive tool provides variety of techniques to display data graphically. You can also annotate
and print graphs for presentations.
3) The Mathematical Function Library: MATLAB provides vast collection of mathematical
algorithms ranging from elementary functions, like sum, sine, cosine, and complex arithmetic like
matrix inverse, matrix eigenvalues, Bessel functions, and fast Fourier transforms, Laplace
transforms, double and triple integral etc.
4) The MATLAB Language: The basic element of MATLAB is array/matrix, which supports control
flow statements, functions, data structures, input/output, and object-oriented programming features.
It has its own internal data types, an extensive catalog of functions, and an environment in which to
develop your own functions and scripts.

IQRA Software All RIGHTS RESERVED 6


5) The Application Programming Interface (API): Suppose you have programs written on C, C++
and FORTRAN and you want to provide interfacing with MATLAB. The MATLAB API provides
special routines (dynamic linking), which interacts with third party software programs. API is a kind
of library.
6) Toolboxes: The Toolbox extends the MATLAB technical computing environment with functions,
plots, and a graphical user interface for exploring, designing, analyzing, and simulating algorithms
for special technologies.
MATLAB supports a family of add-on applications called toolboxes, allow you to learn and apply
specialized technology. Toolboxes are collections of MATLAB script programming functions (M-
files) that extend the MATLAB to solve particular problems. Toolboxes are available including areas
signal processing, communications, data acquisition, financial, control systems, neural networks,
fuzzy logic, simulation etc.
7) Blocksets: The blockset is a tool for simulation and code generation for various types of algorithm
in particular area. You can find number of blocksets in different areas like DSP blocksets belongs to
signal processing, Communications Blockset in Communications areas etc.
It is purely based on modeling, simulation and code generation for various algorithms.

Starting MATLAB
As MATLAB supports Windows and UNIX platforms. You need to know how MATLAB can be started on
both OS.
On Windows platforms, start MATLAB by double-clicking the MATLAB shortcut icon on your Windows
desktop and on UNIX platforms, start MATLAB by typing MATLAB at the operating system prompt.
You can customize MATLAB startup by changing the directory in which MATLAB starts or automatically
execute MATLAB statements in a script file named startup.m.

MATLAB Help
MATLAB provides online help for all its built in functions and programming language constructs. The
commands lookfor, help, helpwin and helpdesk provide online help. MATLAB also has demo programs that
show many of its features. Just type demo at the command prompt to invoke the demo programs.

Types of files
There are three types of files, MATLAB supports to store the information.
1. M-files
2. Mat-files
3. Mex-files

IQRA Software All RIGHTS RESERVED 7


MATLAB Computation
Matrices and Arrays
An array is a list of numbers or expressions arranged in horizontal rows and vertical columns. When an
array has only one row or column, it is called a vector. In MATLAB, a matrix is a rectangular array of
numbers. MATLAB has other ways of storing both numeric and non-numeric data, but it is better to think of
everything as a matrix. Other programming languages work with numbers one at a time, but MATLAB allows
you to work with entire matrices quickly and easily.
The best way for you to start with MATLAB is to learn how to handle matrices. You need to follow a few
basic conventions:
• Use blanks or commas to separate the elements of a row.
• Use a semicolon; to indicate the end of each row.
• Use [ ] square brackets to surround the entire list of elements.
Example:
Simply type the below line to MATLAB command window.
X = [10 3 2 11; 5 12 1 9; 9 6 7 10; 14 15 4 18] OR
X = [10, 3, 2, 11; 5, 12, 1, 9; 9, 6, 7, 10; 14, 15, 4, 18]

The following matrix will be displayed on command window.


X = 10 3 2 11
5 12 1 9
9 6 7 10
14 15 4 18

Once you have entered the matrix, it is automatically stored in the MATLAB workspace with variable name
X. How interesting and simple is it?
If you take the sum along any row or column, you will get the sum of rows/column.
sum(X) returns
ans = 38 36 14 48
sum (X) or sum (X,1), provide the column wise sum.
sum (X, 2) or sum(X')', provide the row wise sum.
Where X’ is the transpose the matrix X.
When you do not specify an output variable, by default MATLAB uses the variable ans, to store the results of
a calculation.

diag (X) provide the diagonal of matrix X.

diag (X) returns

IQRA Software All RIGHTS RESERVED 8


ans = 10
12
7
18

Points to remember
• A vector is a special case of a matrix, with just one row and one column. E.g. x = [1 3 5] is a
row vector and y = [1;3;5] is a column vector.
• A scalar does not need brackets. E.g g = 981
• Square brackets with no elements between them create a null matrix. E.g. a = [ ].
• If it is not possible to type the entire sentence in a line, then use three consecutive periods (…) to
continue to the next line.

E.g. A = [1 3 6; 3 7 …
10; 21 3 11]

Subscripts (Indices)
Once the matrix has been created, its elements can be accessed by specifying their row and column
indices. The element in row i and column j of matrix X is denoted by X (i, j).
X (3, 2) is the element in the third row and second column.

Compute the sum of the elements in the third column of X, type the following
X(1,3) + X(2,3) + X(3,3) + X(4,3)
This produces
ans = 14
If you try to use the value of an element outside of the matrix, it is an error.
t = X(4, 5)
??? Index exceeds matrix dimensions.
If you store a value in an element outside of the matrix, the size increases to accommodate the new coming
value and put three zeros to the fifth column.

A = X;
A(4, 5) = 20

A = 10 3 2 11 0
5 12 1 9 0
9 6 7 10 0
14 15 4 18 20

The use of Colon Operator

The colon : is one of the most important MATLAB operators. It has several uses
The expression 1 : 12 returns row vector containing the integers from 1 to 12,

1 2 3 4 5 6 7 8 9 10 11 12

IQRA Software All RIGHTS RESERVED 9


To obtain spacing, specify an increment.
For example
20:-2:1 is 20 18 16 14 12 10 8 6 4 2

-pi:pi/5:pi is -3.1416 -2.5133 -1.8850 -1.2566 -0.6283 0 0.6283 1.2566

1.8850 2.5133 3.1416


Subscript involving colons of a matrix.
A(1:k, j)
is the first k elements of the jth column of A
Example
A(1:4, 5) or A(1:4, end) returns
ans =
0
0
0
20

Matrix Manipulation

It is easy to correct the wrong entries of a matrix, extract any part of matrix or submatrix of a matrix, delete
or add a row or column. These manipulations are done with MATLAB smart indexing feature. By specifying
vectors as the row and column indices of a matrix one can reference and modify any submatrix of a matrix.
Thus if A is a 10*10 matrix, B is a 5*10 matrix, y is a 20 element long row vector, then
A ([1 3 6 9], :) = [B (1: 3, :); y (1: 10)]
st rd th th
Replaces 1 , 3 , and 6 row of A by the first 3 row of B, and the 9 row of A by the first 10 elements of y.
In this kind of manipulations, it is imperative that the sizes of submatrices to be manipulated are compatible.

Reshaping the matrices: Matrices can be reshaped into a vector or any other proper size of matrix. Let’s
say x is a 6 * 6 matrix
Reshape(x, 9, 4) --- transform x into 9 * 4 matrix,
Reshape(x, 3, 12) --- transform x into 3 * 12 matrix,

Transpose: The transpose of a matrix x is obtained by x’


If x = [2 3; 6 7], then y = x’ gives y = [2 6; 3 7]
Appending a row or column: A row can be easily appended to an existing matrix provided the row has the
same length of rows of existing matrix. The similar concept is applied for column.
If A = [1 0 0;0 1 0;0 0 1], x = [5 6 7] and y = [2;3;4]
Then
A = [A; x] produces A = [1 0 0; 0 1 0; 0 0 1; 5 6 7]

IQRA Software All RIGHTS RESERVED 10


Deleting a row or column: Any row or column of a matrix can be deleted by setting the row or column to a
null vector.
nd
E.g. A(3, :) = [ ] deletes the 2 row of A matrix
A(:, 3:5 ) = [ ] deletes the 3:5 column of A matrix
st rd
A([1 3 ], :) = [ ] deletes the 1 and 3 row of A matrix

In linear algebra, the arithmetic operations on arrays are done element by element. This means that addition
and subtraction are the same for arrays and matrices, but that multiplicative operations are different.
MATLAB uses a dot, or decimal point, as part of the notation for multiplicative array operations.

The Utility matrices: To aid matrix generation and manipulation, MATLAB provides lot of useful utility
matrices

The magic Function: MATLAB has lot of built-in functions; one of them is magic function. The magic
function squares of almost any size.

Example

B = magic(3)

B= 8 1 6
3 5 7
4 9 2
The magic squares returns an n-by-n matrix constructed from the integers 1 through n^2 with equal row and
column sums.

The following are the more built-in function.

eye(m, n) returns m * n matrix with all 1 on the main diagonal.

zeros(m, n) returns m * n matrix of all elements zeros.

ones(m, n) returns m * n matrix of all elements one.

rand(m, n) returns m * n matrix of of random numbers.

rot90 rotates a matrix by 90 degree.

fliplr flip a matrix from left to right

flipud flip a matrix from left to right

reshape changes the shape of the matrix

tril extract the lower triangular part of a matrix

triu extract the upper triangular part of a matrix

IQRA Software All RIGHTS RESERVED 11


Examples:
A = zeros(3, 4) returns

A= 0 0 0 0
0 0 0 0
0 0 0 0

B = ones(3, 3) returns

B= 1 1 1
1 1 1
1 1 1

C = 4*ones(3, 3) returns

C= 4 4 4
4 4 4
4 4 4

R = randn(4, 4) returns

R = -0.4326 -1.1465 0.3273 -0.5883


-1.6656 1.1909 0.1746 2.1832
0.1253 1.1892 -0.1867 -0.1364
0.2877 -0.0376 0.7258 0.1139

You can create your own matrices using M-files, which are text files containing MATLAB code. Save the file
under a name that ends in extension .m.

Creating Vectors: Some time you need to create a vector of numbers over a given range with a specified
increment. The general form of MATLAB command is
X = InitialValue : Increment : FinalValue
If no increment has been specified, MATLAB uses the default increment of 1.
E.g. A = 0:5:50 produces A = [0 5 10 15 20 25 30 35 40 45 50]

There are two other frequently used built-in functions to generate the vectors
linspace(a, b, n) generates a linearly spaced vector of length n from a to b.
a b
logspace(a, b, n) generates a logarithmically spaced vector of length n from 10 to 10 .

IQRA Software All RIGHTS RESERVED 12


Matrix and Arrays operations

Arithmetic operations: The MATLAB matrix vector arithmetic operations are addition (+), subtraction (-)
and multiplication (*). Addition and subtraction are only defined if two matrices have the same dimensions.
Multiplication only works if the matrices have equal inner dimensions, i.e. if A is an n by m matrix and B is an
p by q matrix then A*B is defined if m=p. MATLAB also allows for powers (^) of square matrices.
In addition to a normal division (/), there is a right division (\) in MATLAB. This division is used to solve a
matrix equation. Hence A \ B is almost the same as inv(A)*B, but is faster than computing inv(A)*B directly.
-1
E.g. 4 \ 9 = 9 / 4 = 4 * 9 = 2.25
Arithmetic operations in arrays are slightly different. You can perform arithmetic operations on arrays as
element-by-element basis. Element-by-element multiplication, division and exponentiation between two
matrices of same size are done by preceding the period (.) operator as follows.

.* element-by-element multiplication
./ element-by-element left division
.\ element-by-element right division
.^ element-by-element exponentiation

Relational Operations: There are six relational operators in MATLAB.

A<B less than


A>B greater than
A <= B less than or equal
A >= B greater than or equal
A == B equal
A ~= B not equal

Relational operations are performed element-by-element comparisons between two arrays. They return a
logical array of the same size, with elements set to logical 1 (true) where the relation is true, and elements
set to logical 0 (false) where it is not.

Example: Let x = [1 5 3 7] and y = [0 2 8 7]

K=x<y results in k = [0 0 1 0]
K=x<=y results in k = [0 0 1 1]
K=x>y results in k = [1 1 0 0]
K=x>=y results in k = [1 1 0 1]
K=x==y results in k = [0 0 0 1]
K=x~=y results in k = [1 1 1 0]

IQRA Software All RIGHTS RESERVED 13


Logical Operations: There are four types of logical operators.

& elementwise logical AND


| elementwise logical OR
~ elementwise logical complement (NOT)
xor exclusive OR

These operators work in a similar way as the relational operators and produce vectors or matrices of same
size as the operand, with 1 when condition is true and 0 when false.
Apart from four there are two Short-circuit operators
&& Short-circuit AND
|| Short-circuit OR
Example: Let x = [1 5 3 7] and y = [0 2 8 7]
K = (x>y)&(x>4) results in k = [0 1 0 0]
K=x|y results in k = [0 1 1 1]
K = ~(x | y) results in k = [1 0 0 0]
K = xor(x, y) results in k = [0 0 0 0]

In addition to these logical operators, there are many useful built-in logical functions as follows.
all true (1) if all elements of a vector are true.
e.g. all (x>0) returns 1 if each element of x is positive.
any true (1) if any element of a vector is true.
exist true (1) if a variable or function exists.
isempty true for an empty matrix
isinf true for all infinite elements in a matrix
isfinite true for finite elements in a matrix
isnan true for all elements in a matrix are not a number
find it finds indices of non-zero elements in a matrix

Expressions

Almost every programming language supports expression. MATLAB provides mathematical expressions, but
unlike most programming languages, these expressions involve entire matrices.
The expressions can be classified as follows

Variables

MATLAB does not need any type declarations. When you enter a new variable name, MATLAB
automatically creates the variable, allocates the appropriate amount of data storage and store into
workspace. If the variable already exists, MATLAB updates its value. It also identifies the type of data you
have entered.

IQRA Software All RIGHTS RESERVED 14


Example
students = 40

Creates 1*1 matrix under the variable name of students and stores the single value in it.
Variable names can have of a letter, followed by any number of letters, digits, or underscores. MATLAB
uses only the first 31 characters of a variable name.
Keep in mind that MATLAB is a case sensitive. The A and a are not the same variable.

Numbers
MATLAB uses decimal notation, with an optional decimal point and leading plus or minus sign, for numbers.
Scientific notation uses the letter e to specify a power-of-ten as a scaling factor. Imaginary numbers use
either i or j as a suffix.
Example
2 -5 0.0056 2i + 3j 2.0356e+9
All numbers will be stored using the long format specified by the IEEE floating-point standard.

Operators
Like in other language, MATLAB expressions use operators, precedence wise listed in below table.

Operators Performed Operations


+ Addition
- Subtraction
* Multiplication
/ Division
\ Left division
^ Power
‘ Complex conjugate transpose
() Specify evaluation order
Table 1: Operators in MATLAB Language

Functions
MATLAB language library contains a large number of standard elementary mathematical functions like abs,
sqrt, exp, and sin etc. Taking the square root or logarithm of a negative number is not an error; the complex
result is produced automatically. It also provides many more advanced mathematical functions like Bessel
and gamma functions. Most of these functions accept complex arguments.

For a list of the elementary mathematical functions, type the following


help elfun
For a list of more advanced mathematical and matrix functions, type the following
help specfun
help elmat

Functions can be defined in two categories as Built-in and M-file functions.


The details will be discussed later.

IQRA Software All RIGHTS RESERVED 15


Loading and saving the matrices

There is load function, which loads the matrices from workspace, already generated by MATLAB.
The load function reads binary data from the workspace or text file. The text files should be having
rectangular table of numbers, separated by blanks, with one row per line, and an equal number of elements
in each row.
load sum_data.dat

This statement reads the file from workspace and creates all variable, stored in it.
There is a save function, which saves workspace variables to disk. It saves all workspace variables to the
binary "MAT-file" named FILENAME.mat. MAT-files created with save function are by-default compressed
and char arrays are encoded using Unicode.

Concatenation of matrices
It is the process of joining small matrices into bigger ones. First create a small matrix as
A = 4*ones(3, 3), returns 3 by 3 matrix of all elements are 4.

Concatenate using following expression,


B = [A A+26; A+35 A+11], returns

B= 4 4 4 30 30 30
4 4 4 30 30 30
4 4 4 30 30 30
39 39 39 15 15 15
39 39 39 15 15 15
39 39 39 15 15 15

The below is the list of operators


Operators Performed Operations
+ Addition
- Subtraction
.* Element-by-element multiplication
./ Element-by-element Division
.\ Element-by-element Left division
.^ Element-by-element Power
.‘ Unconjugated array transpose
Table 2: Operators in MATLAB Language

Scalar operations in Matrices


Matrices and scalars can be combined in several different ways.

IQRA Software All RIGHTS RESERVED 16


Example
A = 16 3 2 13
5 10 11 8
9 6 7 12
4 15 14 1

B = A – 15, returns
B= 1 -12 -13 -2
-10 -5 -4 -7
-6 -9 -8 -3
-11 0 -1 -14

You can assign a specified scalar to any index.


B(1:2, 2:3) = 20

B= 1 20 20 -2
-10 20 20 -7
-6 -9 -8 -3
-11 0 -1 -14
The value 20 has been assigned to said indices.

The find Function

The find function determines the indices of array elements based on a given logical condition.
k = find(isprime(A)) returns,
k=2
5
9
10
11
13

It picks out the prime number locations and displays the indices of prime numbers in the matrix.
It’s very much useful in scientific applications.

How to control command window Input and Output

Till now you have used MATLAB command line, functions and expressions, and seeing the results printed in
the Command Window. This section describes how to control the command window input and output.
Format Function
MATLAB displays the variables values in command window. The FORMAT is a function, which controls the
numeric format of the values.

IQRA Software All RIGHTS RESERVED 17


Example
x = [5/3 2.345e-6]
format short e, x returns
x = 1.6667e+000 2.3450e-006
format long, x returns
x = 1.66666666666667 0.00000234500000
format short g, x returns
x = 1.6667 2.345e-006
format rat, x returns
x = 5/3 1/426439
format hex, x returns
x = 3ffaaaaaaaaaaaab 3ec3abd962317873

Format is a very useful function, it affects only how numbers are getting displayed on command window, and
not how MATLAB saves them into workspace.
Format Command Result Example

Format Default Same as short

Format short 5 digit scaled fixed point 3.1416

Format long 15 digit scaled fixed point 3.14159265358979

Format short e 5 digit floating-point 3.1416e+00

Format long e 15 digit floating-point 3.141592653589793e+00

Format short g Best of 5 digit fixed or floating 3.1416

Format long g Best of 15 digit fixed or floating 3.14159265358979

Format hex Hexadecimal 400921fb54442d18

Format bank Fixed dollars and cents 3.14

Format rat Ratio of small integers 355/113

Format + +, - +3.1416

Table 3: Format commands in MATLAB Language

IQRA Software All RIGHTS RESERVED 18


Suppressing Output

If you simply type a statement and press Enter on command window, MATLAB automatically displays the
results on screen. If you end the line with a semicolon, MATLAB performs the computation and store the
variable in workspace, but does not display any output. This is particularly useful when you generate large
matrices.

Example

A = magic(100);

Entering Long Statements

If you are typing a long statement and statement does not fit in one line of command window. Now if you
Enter, MATLAB does not produce the correct result.

You need to use an ellipsis (three periods) i.e. … and Enter, then MATLAB understand the statement
continues to the next line.
Example
A = 1 -1/2 + 1/3 -1/4 + 1/5 - 1/6 + 1/7...
- 1/8 + 1/9 - 1/10 + 1/11 - 1/12;

IQRA Software All RIGHTS RESERVED 19


Programming in MATLAB

MATLAB is a high-level language that includes matrix-based operations. It supports data structures, its own
internal data types, an extensive catalog of functions, an environment in which to develop your own
functions and M-File Programming etc. MATLAB has a distinguish feature i.e. ease to use by user written
programs. It provides its own language, which incorporate many features from C language. It is a high level
language than other programming languages like FORTRAN, Pascal, and C.

Control Constructs
MATLAB has its own syntax for control flow statements like for loop, while loop and if-else branching. It also
provides three commands break, error, and return to control the execution of the program. The details are as
follows.

IF-else Statement
If statement evaluates a logical expression and executes a group of statements when the expression is true,
the else and elseif are optional. The end word, terminates the if statement.
It’s a good idea to include a default else to catch cases that do not match the preceding if and elseif blocks.
There braces or brackets are not involved.
Example
if x > 0
disp(’x is positive’);
elseif x < 0
disp(’x is negative’);
else
disp(’x is exactly zero’);
end

Switch and case


The switch statement executes groups of statements based on the value of a variable or expression. Only
the first matching case is executed. There must always be an end to match the switch. The break statement
is not required.
Example
switch lower(method)
case {'linear','bilinear'}
disp('Method is linear')
case 'cubic'
disp('Method is cubic')
case 'nearest'
disp('Method is nearest')

IQRA Software All RIGHTS RESERVED 20


otherwise
disp('Unknown method.')
end

For Statement
The for loop repeats a group of statements for a fixed number of times. A matching end delineates the
statements. The for loop repeats statements a specific number of times. The for statement is used, where
the number of iterations are known in advance. Every for loop must be matched with an end statement.
The for loops are used when each element in a vector or matrix is to be processed.
Example
x = 1:5; % create a row vector
sum = 0; % initialize the sum
for k = 1:length(x)
sum = sum + x(k);
end
While Statement
WHILE loop used to execute statement or a group of statements for an indefinite number of times based on
logical condition is satisfied. A while loop must have a matching end statement.
while loops are most often used when an iteration is repeated until some termination criterion is met.
The BREAK statement can be used to terminate the loop prematurely.
The return is used to force an exit from a function. This can have the effect of escaping from a loop. Any
statements following the loop that are in the function body are skipped.
Example
x = rand(1,n);
k = 1;
while k<=n
if x(k)>0.8
return
end
k = k + 1;
end
Continue
The continue statement passes program control to the next iteration of the for loop or while loop in which it
appears, skipping any remaining statements in the body of the loop.
Break
The break statement inside a for loop or while loop terminates the execution of the loop, even if the condition
for loop is true. In nested loops, break terminates from the innermost loop only.
The break is used to escape the current while or for loop, while the return is used to escape the current
function.
Example
for i = 1:10
If u(i) < 0

IQRA Software All RIGHTS RESERVED 21


break
end
x = v(i) +10
end

try – catch
The general form of a try-catch statement is
try
statement
...
statement
catch
statement
...
statement
end
The statements between the try and catch are executed. If an error occurs while executing any of the
statements, the error is captured into lasterr and the statements between the catch and end are executed.
If an error occurs within the CATCH statements, execution will stop.
It is very much useful in scientific applications.

Error
The error command inside a function or a script terminates the execution, displays the error message and
return the control to the keyboard.
Example
Error (‘?? Wrong dimensions for matrix multiply')

M-File Programming

If you are writing program in MATLAB, you need to save it in a file with .m (extension .m). These files are
called M-files and the programs are called M-file programs. This technique of writing M-file programming is
called M-file programming.
There are two types of M-files i.e. script and function.

Scripts are simple series of MATLAB statements. You can write a simple MATLAB statement in a file and
save it to file_name.m. The M-file containing series of statements are called scripts. A script file is executed
by typing the name of the file (without .m) on the command window.
A script file may contain any number of commands including built-in functions as well as user defined
functions. Script files are useful when you have to repeat a set of commands several times.
MATLAB scripts contains the following features
• Useful for automating a series of steps that you need to perform many times.
• Neither accepts any input arguments nor returns any output arguments.
• Store all variables in workspace that is shared with other scripts.

IQRA Software All RIGHTS RESERVED 22


Now you see how to write a script file. Following are the steps.

1. Use "New, M-File" under file menu or use any text editor
2. Type in a series of commands, such as
o t1 = 0:0.1:50;
o y1 = sin(t);
o t2 = 0:0.1:50;
o y2 = cos(t);
o plot(t1,y1,'r-',t2,y2,'g:')
o legend('Y1 = SIN','Y2 = COS')
o xlabel('Time (Seconds)')
o ylabel('Amplitude (Meters)')
o title('Plot Trigonometry Equations')
3. Save as file name plottrig.m
4. In the Matlab window, type in plottrig and it will run your series of commands.
5. Any text following a percent sign (%) is treated as a comment by Matlab.

After running of script file, you can find lot of variables stored in MATLAB workspace and the value of
variable can be seen by typing the variable name on MATLAB command window.
Now on the other hand if you want to do a big set of computations, but at the end you want only few
variables stored in workspace, a script file is not the right choice. Here you need to use a function file.
MATLAB functions are the simple series of MATLAB statements and a unique function name in the first line,
having input/output arguments. Every MATLAB function has its definition line, which informs MATLAB that
the M-file contains a function, and specifies the I/O arguments. The function names must begin with a letter,
may contain any alphanumeric characters or underscores, and must be no longer than the maximum
allowed length.

The name of the M-file that contains a MATLAB function consists of the function name with the extension .m
appended. The filename and the function definition line name are must be same.

IQRA Software All RIGHTS RESERVED 23


Example
function f = add(a, b) %Function definition line
% Compute a addition value.
% ADD(a, b) returns the addition of a and b,

% Put simply, ADD(A, B) is add(a, b).


f = add(a, b); %Function body

MATLAB functions contains the following features


• Useful for extending the MATLAB language for application.
• Can accept input arguments and return output arguments.
• Store variables in a workspace internal to the function.

Following are the steps to write a function

o function y = aveVal(x)
o % AVERAGE Mean of vector elements.
o % AVERAGE(X), where X is a vector, is the mean of vector % elements.
o % Nonvector input results in an error.
o [r,c] = size(x);
o if (~((r == 1) | (c == 1)) | (r == 1 & c == 1))
o error('Input must be a vector')
o end
o y = sum(x)/length(x); % Actual computation

Enter the following command to get the result


x = 1 : 20;
y = aveVal(x) returns
y = 10.500

Keep in mind that MATLAB always passes argument data by value only.

When you call a M-file function from either the command line or from another M-file, MATLAB resolves the
function into pseudo code and stores it in memory. This prevents MATLAB from having to re-describe a
function each time you call it during a session. The pseudo code remains in memory until you clear it using
the clear function, or until you quit MATLAB session.
MATLAB functions can be classified as follows

• Primary M-File Functions: Simple function


• Subfunctions: Additional functions within the file
• Nested Functions: Functions within another function

IQRA Software All RIGHTS RESERVED 24


• Anonymous Functions: abc = @(x) exp(x), without function format
• Private Functions: Reside in subdirectories with the special name private

Determine Which Function Is Called

If you saved more than one function by the same name, which one should be called by MATLAB?
The following is the order, which MATLAB adopt to call the function
• Function Scope
• Precedence Order: Variable, Subfunction, Private function, Function in the current directory,
Function elsewhere on the path.
• Multiple Implementation Types: MEX-files, MDL-file, P-code, M-file or built-in (.bi) file.
Keep in mind that M-file functions do not require a end statement to terminate the statement. If an M-file
contains one or more nested functions, you must terminate all functions in the M-file with end statement.
Example
Function x = Alpha(p1, p2)
...
function Beta = B(p3)
...
end

function z = Gama(p4)
...
end
...
End
Here each function, as well as nested function is terminated by end statement.
Points to remember
• Never name the script file the same as the name of variable, it computes E.g. If you execute a
MATLAB file xdot.m and that computes a variable xdot. After the first execution of file, the xdot
variable stored in MATLAB workspace. Now if again you want to execute the xdot.m file, the file will
not be executed.
• The name of the script file must begin with a letter. The rest of the characters may include digits
and underscore character. You can give long name as you want, but MATLAB will take only first 19
characters. You can not use the dot (.) in the name other than the last one (.m).
• Be careful with variable names while working with script files, because all variables generated by a
script file are stored in workspace, unless you clear them. Avoid name clashes with built-in function.
Executing a function
The built-in or user written functions can be executed by two ways.
1. With explicit output: This is a full syntax of calling a function. Both the output and the input list
are specified in the call. For example, if the function definition line of a function reads.
function [L, H, F] = distance (x, y, t);

IQRA Software All RIGHTS RESERVED 25


Then all the following commands represent legal call (execution) statement:
• [r, angmom, force] = distance (xt, yt, time); the input variable xt,yt,and time must be defined before
execution this commond.
• [reg, mye, F] = distance(2, 7, 101); All input values are specified in the call.
2. Without any output: The output list can be omitted entirely if the computed quantities are not of
any interest or you do not want the output variables to be displayed. This might be the case when
the function displays the desired result graphically. To execute the function this ways, just type the
name of the function with the input list.
For example, distance (xt, yt, time); will execute the function motion without generating any
explicit output. Provided that xt, yt, and time are defined. If the semicolon at the end of the call
statement is omitted, the first output variable in the output list of the function is displayed in the
default variable ans.

Data Import and Export


There are many ways to load data from files or the clipboard into the workspace, process called importing
data and to save workspace variables to a disk file, process called exporting data.
There are two major factors, you need to take care.
• Remember either you are importing or exporting data.
• The format of the data like textual, binary, or a standard format such as HDF.
MAT files: MAT-files are double-precision binary MATLAB format files, created by the save function and
read by the load function.

There are many ways to import the data of different format, which are as follows.
The load Function: It imports variables from a binary or ASCII file into your workspace.
load filename, loads all variables from the workspace.
load filename var1 var2 ... varN, loads particular variables from the workspace.
The csvread Function: Read a comma-separated value file.
M = csvread('filename', row, col), reads data from the comma-separated value formatted file
starting at the specified row and column.
The dlmread Function: Read an ASCII-delimited file into a matrix.

A = dlmread('ph.dat', ';'); reads, numeric data from the ASCII-delimited file filename ph.dat, using a
delimiter inferred from the formatting of the file. Comma (,) is the default delimiter.
The textread Function: Read data from text file, write to multiple outputs.
[names, types, x, y, answer] = textread('mydata.dat', ... '%s %s %f %d %s', 1), Read the first line of
the file as a free format file using the % format.
There are many ways to export the data of different format, which are as follows.
The save Function: It save workspace variables on disk.
save('abc'), stores all workspace variables in a binary format in the current directory in a file named
abc.mat. If no file name is given, by default it store the data in matlab.mat file.

save('filename', 'var1', 'var2', ...), stores var1 and var2 in given file.

IQRA Software All RIGHTS RESERVED 26


The csvwrite function: Write a comma-separated value file.
Example
a = [2 4 6 8 10; 4 8 12 16 20; 6 12 18 24 30; 8 16 24 32 40];
csvwrite('csvfile.dat',a);
type csvfile.dat, returns
2 4 6 8 10
4 8 12 16 20
6 12 18 24 30
8 16 24 32 40

The dlmwrite Function: Write a matrix data to an ASCII-delimited file.


Example
M = magic(4)

dlmwrite('myfile.txt', [M], ' ')


load myfile.txt, it save data to workspace with variable name myfile.MAT.
type myfile, which returns

16 2 3 13
5 11 10 8
9 7 6 12
4 14 15 1
The diary Function: It save session to a file.
diary filename causes a copy of all subsequent command window inputs and most of the resulting command
window outputs to be appended to the file. If no file is mentioned, the file 'diary' is used.
A good way to work with MATLAB is to use it interactively, and then edit you session and save the edited
commands to a script file. You can save the session either by cutting and pasting or by turning on the diary
feature.

Advanced Data Objects


The most familiar data object, a matrix has been transformed. Now it can be a multidimentional. The fact is
that these objects as well as a matrix are just a special case of fundamental data type i.e. array.
The basic data structure in MATLAB is the matrix: a two-dimensional data structure capable of storing
multiple elements of data in an easily accessible format. These data elements can be numbers, characters,
and logical states of true or false, or even other MATLAB structure types.
MATLAB also supports data structures that have more than two dimensions. These data structures are
referred as arrays in the MATLAB history.

Creating Matrices and Multidimensional Arrays


Multidimensional arrays are arrays with more than two subscripts. You can create n-dimensional matrices by
specifying n indices. The matrix creation functions like zeros, ones, rand and randn accept n indices to
create such matrices.

IQRA Software All RIGHTS RESERVED 27


Example
R = randn(2, 3, 4);
It creates a 2-by-3-by-4 array with a total of 2x3x4 = 24 normally distributed random elements.
A = zeros(4, 5, 3);initializes 4 * 5 * 3 matrix of A.
B = rand(3, 5, 6, 2); creates 3 * 5 * 6 * 2 random matrix B.
The other way to create a multidimensional array is to create a two-dimensional array and extend it.
Example
A = [2 3 5; 0 6 8; 3 7 9]; returns
A= 2 3 5
0 6 8
3 7 9
A is a 3-by-3 array, that is, row dimension is 3 and column dimension is 3. To add a third dimension to A,
A(:, :, 2) = [2 0 3; 2 7 9; 8 5 4]; returns

A(:, :, 1) = 2 3 5
0 6 8
3 7 9

A(:, :, 2) = 2 0 3
2 7 9
8 5 4
To extend multidimensional array A in any dimension:
• Increment or add the appropriate subscript and assign the desired values.
• Assign the same number of elements to corresponding array dimensions. For numeric arrays, all
rows must have the same number of elements; all pages must have the same number of rows and
columns, and so on.
It is called the MATLAB scalar expansion.
There is one more function called cat, which is used to build multidimensional arrays; it concatenates a list
of arrays along a specified dimension:

Example
B = cat(dim, A1, A2...)
Where A1, A2, are the arrays to concatenate and dim is the dimension along which to concatenate the
arrays.
B = cat(3, [2 8; 0 5], [1 3; 7 9]) returns
B(:,:,1) = 2 8
0 5

B(:,:,2) = 1 3
7 9

IQRA Software All RIGHTS RESERVED 28


Cell arrays are also multidimensional arrays whose elements are copies of other arrays. A cell array of
empty matrices can be created with the cell function. The cell arrays are created by enclosing a
miscellaneous collection of things in curly braces {}.
A cell is the most versatile data object in MATLAB. It can contain any type of data such as an array of
numbers, strings, and structures or cells itself. An array of cell is called cell array.
The cell array can be thought of as an array of data containers. You can imagine cell arrays as follows.
Put nine empty boxes on the floor in 3 rows and 3 columns. Now put clothes in one box, shoes in second
box, a computer in third box, a set of bottles in fourth box and so on till ninth box is filled. Each box is a
container, while the content of each box are different. Thus we have an arrangement that can accommodate
all kinds of things in the containers. The combination of all kind of containers is called the cell array.

Example
C = cell(2,2); %create a 2 * 2 cell
C{1,1} = rand(3); %put 3 * 3 rand matrix in first box
nd
C{1,2} = char(‘amit’, ‘mohan’); %put a string array in 2 box
rd
C{2,1} = struct_str; %put a structure in 3 box
th
C{2,2} = cell(3,3); %put 3 *3 cell in 4 box

It produces a 2-by-2 cell array. In this example creating a cell looks like creating an ordinary array, but
having some major differences. First the contents are as varied as user want to be. Second there are curly
braces instead of parenthesis on left side of assignment. So why we use curly braces? Why don’t
parenthesis?
A cell is different from ordinary array in that it distinguishes between containers and the contents and it
allows to access both separately. If you treat a cell like an array, so you can access the element by C(i, j).
So what you will get, the container located at ith row and jth column. If you want to access the contents of
the container, you have to use a special cell-content-indexing method using curly braces. Hence type C{i, j}
instead of C(i, j). So curly braces are used for cell and square braces are used for arrays.

You can also create cell array directly as


C = {rand(3), char((‘amit’, ‘mohan’), struct_str, cell(3,3)};
struct_str =
{ struct(‘course’, CS202, ‘prof’, ‘score’ [52 34 91];
struct(‘course’, EI302, ‘prof’, ‘score’ [12 45 69];
struct(‘course’, CE305, ‘prof’, ‘score’ [21 45 77];};

C = cell(2,2);
C{1,1} = rand(3);
C{1,2} = char(‘amit’, ‘mohan’);
C{2,1} = struct_str;
C{2,2} = cell(3,3);

IQRA Software All RIGHTS RESERVED 29


Just type C, it returns
[3 * 3 double] [2 * 4 char]
[3 * 1 struct] [3 * 3 cell]
type C{1, 2}, it returns
ans = amit
mohan

We will discuss about the Characters and Text. Enter text into MATLAB using single quotes.
Example
s = 'Hello' returns

s = Hello

It is a 1-by-5 character array. Internally, the characters are stored as numbers, but not in floating-point
format. The statement
a = double(s) returns

a = 72 101 108 108 111


It converts the character array to a numeric matrix containing floating-point representations of the ASCII
codes for each character.
The statement
s = char(a) returns

s = Hello

again reverses the conversion.

Structures are multidimensional arrays with elements accessed by textual field designators. A structure is a
data with several named fields. Different fields can have different types of data, but a single field must have
data of same type.
A structure is like a record. One record contains information about various things under different heads as
relationship, address, name of children, DOB etc. Although headings are same in each record, but the
information under each headings will vary from record to record.

Example
S.name = 'A Mohan';
S.score = 103;
S.grade = 'A'; S.team = 'DC';

Creates a structure with four fields.


S = name: 'A Mohan'
score: 103

IQRA Software All RIGHTS RESERVED 30


grade: 'A'
team: 'DC'

There is way to extend the structure like


S(2) = struct('name', 'Rohan', 'score', 125, 'grade', 'B', 'team', 'BC')

Now if you type S and return,


S = 1x2 struct array with fields:
name
score
grade
team
You can access the each member of structure by typing
S(1).name, return
A Mohan
S(2).team, returns
BC
Specialized Matrix Functions
MATLAB has a number of functions that create different kinds of matrices. Some of them are listed in the
table.
Function Description

ones Create a matrix or array of all ones.

Zeros Create a matrix or array of all zeros.

Eye Create a matrix with ones on the diagonal and zeros elsewhere.

accumarray Distribute elements of an input matrix to specified locations in an output matrix, also
allowing for accumulation.
diag Create a diagonal matrix from a vector.

magic Create a square matrix with rows, columns, and diagonals that add up to the same
number.
rand Create a matrix or array of uniformly distributed random numbers.

randn Create a matrix or array of normally distributed random numbers and arrays.

randperm Create a vector (1-by-n matrix) containing a random permutation of the specified
integers.
Table 4: MATLAB Functions to create matrices

IQRA Software All RIGHTS RESERVED 31


Dimensions of the Matrix
Function Description

length Return the length of the longest dimension. (The length of a matrix or array with any
zero dimension is zero.)
ndims Return the number of dimensions.

numel Return the number of elements.

size Return the length of each dimension.

Table 5: MATLAB Functions to identify shape and size of a matrix

Reshaping a Matrix
The following functions change the shape of a matrix.
Function Description

reshape Modify the shape of a matrix.

rot90 Rotate the matrix by 90 degrees.

fliplr Flip the matrix about a vertical axis.

flipud Flip the matrix about a horizontal axis

flipdim Flip the matrix along the specified direction.

transpose Flip a matrix about its main diagonal, turning row


vectors into column vectors and vice versa.
ctranspose Transpose a matrix and replace each element with
its complex conjugate
Table 6: MATLAB Functions to re-shape a matrix

Shift and Sort Functions


These are the functions to shift or sort the elements of a matrix.
Function Description

circshift Circularly shift matrix contents

sort Sort array elements in ascending or descending

IQRA Software All RIGHTS RESERVED 32


order.
sortrows Sort rows in ascending order.

issorted Determine if matrix elements are in sorted order.


Table 7: MATLAB Functions to shift & short a matrix

The circshift function shifts the elements of a matrix in a circular manner along one or more dimensions.
Rows or columns that are shifted out of the matrix circulate back into the opposite end.
Example
A = [1:5; 6:10; 11:15; 16:20; 21:25] returns

A= 1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
16 17 18 19 20
21 22 23 24 25
B = circshift(A, [0, 3]) returns

B= 3 4 5 1 2
8 9 10 6 7
13 14 15 11 12
18 19 20 16 17
23 24 25 21 22
B = circshift(A, [3, 0]) returns
B= 11 12 13 14 15
16 17 18 19 20
21 22 23 24 25
1 2 3 4 5
6 7 8 9 10

Diagonal Matrices
These are the functions that work specifically on diagonal matrices.
Function Description

blkdiag Construct a block diagonal matrix from input


arguments.
diag Return a diagonal matrix or the diagonals of a
matrix.
trace Compute the sum of the elements on the main
diagonal.
tril Return the lower triangular part of a matrix

IQRA Software All RIGHTS RESERVED 33


triu Return the upper triangular part of a matrix

Table 8: MATLAB Functions for diagonal matrix

Generate the matrix using diag function


Example
A = diag([12:4:24]) returns

A= 12 0 0 0
0 16 0 0
0 0 20 0
0 0 0 24

Find the diagonal of a matrix


Example
A = magic(4) returns

A= 16 2 3 13
5 11 10 8
9 7 6 12
4 14 15 1

diag(A) returns

ans = 16
11
6
1
diag(A, 1) returns

ans = 2
10
12

diag(A, 3) returns

ans = 13
Matrices Definition
An empty matrix having at least one dimension equal to zero is called an empty matrix.

IQRA Software All RIGHTS RESERVED 34


Example
A = []; is an empty matrix

A = zeros(0, 9) is an empty matrix, returns

Empty matrix: 0-by-9


Any individual real or complex number is represented in MATLAB as a 1-by-1 matrix called a scalar matrix:
Example

A = 10;

A = 2i + 3j
Matrix, which is having one dimension equal to one and the other dimension greater than one is called
vectors matrix.
Example
A = [10 24 87 19 6];
It is common to have matrices with a large number of zero-valued elements and, because MATLAB stores
zeros in the same way it stores any other numeric value, these elements can use memory space
unnecessarily and can sometimes require extra computing time.
Sparse matrices provide a way to store data that has a large percentage of zero elements more efficiently.
While full matrices internally store every element in memory regardless of value, sparse matrices store only
the nonzero elements and their row indices. Using sparse matrices can significantly reduce the amount of
memory required for data storage.

Sparse matrices are a special kind of matrices that contain number of zero-valued elements. This property
allows MATLAB to:
• Store only the nonzero elements of the matrix, together with their indices.
• Reduce computation time by eliminating operations on zero elements.

Example
A= 0 0 0 5
0 2 0 0
1 3 0 0
0 0 4 0

S = sparse(A) returns
S= (3,1) 1
(2,2) 2
(3,2) 3
(4,3) 4
(1,4) 5

IQRA Software All RIGHTS RESERVED 35


This table shows some of the functions used, working with sparse matrices.

Function Description

full Convert a sparse matrix to a full matrix.

issparse Determine if a matrix is sparse.

trace Compute the sum of the elements on the main diagonal.

nnz Return the number of nonzero matrix elements.

nonzeros Return the nonzero elements of a matrix.

nzmax Return the amount of storage allocated for nonzero elements.

spalloc Allocate space for a sparse matrix.

sparse Create a sparse matrix or convert full to sparse.

speye Create a sparse identity matrix.

sprand Create a sparse uniformly distributed random matrix.

Table 9: MATLAB Functions for sparse matrices

Error Handling
In most of cases, it is necessary to take required actions for various kinds of errors occur. A good
documentation is very important but it is also useful to include some error checking in your programs. This
makes it much easier to track down the nature of problems when they arise.
You have written and tested a program, it does not mean that your program always run as smoothly as
expected when run under different conditions.

If some statements in your code generate unwanted results, put those statements into a try-catch block that
will catch any errors and handle them properly.
Example
function X = matrixAdd(A, B)

try
X = A + B;
catch
disp 'Error Adding matrices A + B'
end

A = [1 2 3; 6 7 2; 0 1 5];

B = [9 5 6; 0 4 9];

IQRA Software All RIGHTS RESERVED 36


When you execute the above example, MATLAB catches the error and displays the message generated in
the catch section of the try-catch block.

matrixAdd(A, B), returns

Error Adding matrices A + B


A try-catch block is divided into two parts.
• All statements in the try segment are executed normally. But if any of these statements produced
an error, MATLAB skips the remaining statements in the try and jumps directly to the catch
segment of the block.
• The catch segment handles the error and displays a respective error message.
Try-catch block does not halt the program execution.
To report an error and halt program execution, use MATLAB error function.
Example
if a < 1
error('a must be 1 or greater.')
end

displays the message shown below when a is equal to zero.


??? a must be 1 or greater.
File input/output operations

MATLAB file input and output (I/O) functions read and write arbitrary binary and formatted text files. This
enables you to read data collected in other formats and to save data for other programs, as well. Before
reading or writing a file you must open it with the fopen command:
fid = fopen (file_name, permission);
The permission string specifies the type of access you want to have:
’r’ - for reading only
’w’ - for writing only
’a’ - for appending only
’r+’ - both for reading and writing
Example
fid = fopen (’results.txt’,’w’);
The fopen statement returns an integer file identifier, which is a handle to the file (used later for addressing
and accessing your file). When fopen fails (e.g. by trying to open a non-existing file), the file identifier
becomes −1. It is also possible to get an error message, which is returned as the second optional output
argument.
It is a good habit to test the file identifier each time when you open a file, especially for reading. Below, the
example is given, when the user provides a string until it is a name of a readable file:
When you finish working on a file, use fclose to close it up. Matlab automatically closes all open files when
you exit it. However, you should close your file when you finished using it:
fid = fopen (’results.txt’, ’w’);

IQRA Software All RIGHTS RESERVED 37


...
fclose(fid);
Low level File I/O:
• Use to read files in any formats
• fopen: open a file
• fclose: close a file
• fread, fscanf: read from a file
• fwrite,fprintf: write to a file
• fgetl: read a line from file

Examples: The below are some examples to understand the file I/O concept
fid = fopen('matrix.bin',‘r')
[a, n]=fread(fid,‘int32');
fclose(fid)

fid=fopen('aphabet.txt',‘r');
[s, c]=fread(fid);
fclose(fid);

fid = fopen('mydata.dat','w');
fprintf(fid,'%f',pi);
fclose(fid);

Efficient way to write Matlab programs


Never write all code at once; program in small steps and make sure that each of these small steps works as
expected, before proceeding to the next one. Each step should be devoted to only one task. Do not solve
too many tasks in one module, because you may easily make a mistake. This is called a structured or
modular way of programming. The benefit of structural programming are:
easier error detection and correction, modifiability, extensibility and portability.
A general approach to a program development is presented below:
1. Specification: Read and understand the problem. The computer can not do any thing itself; you
have to tell it how to operate. Before using the computer, some level of preparation and thoughts
are required. Some basic questions to be asked are:
• What are the parameters/inputs for the problem?
• What are the results/outputs for the problem?
• What form should the inputs/outputs be provided in?
• What sort of algorithms is needed to find the outputs from the inputs?

2. Design: Split your problem into a number of smaller and easier tasks. Decide how to implement
them? Start with a schematic implementation to solve your problem, e.g. create function headers or
script descriptions (decide about the input and output arguments). To do this, you may use, for

IQRA Software All RIGHTS RESERVED 38


example, a top-down approach. You start at the most general level, where your first functions are
defined. While ’going down’ your functions become more precise and more detailed.
3. Coding: Implement the algorithms sequentially (one by one). Turning your algorithm into an
efficient code is not a one-shot process. You will have to try, make errors, correct them and even
modify the algorithm. So, be patient. While implementing, make sure that all your outputs are
computed at some point.
4. Running and debugging: Bugs will often exist in a newly written program. Never, ever, believe or
assume that the code you just created, works. Always check the correctness of each function or
script: Twice. You may add some extra lines to your code which will present the intermediate
results (screen displays, plots, writes to files) to help you controlling what is going on. Those lines
can be removed later.
5. Testing and Verification: After the debugging process, the testing stage starts. Prepare a number
of tests to verify whether your program does what it is expected to do. Remember that good tests
are those for which the answers are known. Your program should produce correct results for
normal test conditions as well as boundary conditions.
6. Maintenance: In solving your task, new ideas or problems may appear. Some can be interesting
and creative and some can help you to understand the original problem better; you may see an
extent to your problem or a way to incorporate new things. If you have a well-designed problem,
you will be able to easily modify it after some time. Take a responsibility to improve your solutions
or correct your errors when found later.

Debugging: Debugging is the process by which you identify and fix any problem with your code. Two kinds
of errors may occur: syntax error and runtime error. Syntax errors can usually be easily corrected by
MATLAB error messages. Runtime errors are algorithmic in nature and they occur when e.g. you perform a
calculation incorrectly. They are usually difficult to track down, but they are apparent when you notice
unexpected results.
Debugging is an inevitable process. The best way to reduce the possibility of making a runtime error is
defensive programming:
• Do not assume that input is correct, simply check.
• Where reasonable and possible, provide a default option or value.
• Provide diagnostic error messages.
• Optionally print intermediate results to check the correctness of your code.

MATLAB provides an interactive debugger. It allows you to set and clear breakpoints, specific lines in an m-
file at which the execution halts. It also allows you to change the workspace and execute the lines in an m-
file one by one. The MATLAB m-file editor also has a debugger. The debugging process can be also done
from the command line. To use the debugging facility to find out what is happening, you start with the
dbstop command. This command provides a number of options for stopping execution of a function.

IQRA Software All RIGHTS RESERVED 39


MATLAB Data Types
MATLAB supports 15 fundamental data types. Each of these data types is in the form of a matrix or array.
This matrix or array is a minimum of 0*0 size or n-dimensional.
Two-dimensional versions of these arrays are called matrices.
The data types of an array can be classified as follows.
• Logical
• Char
• Numeric
• Cell
• Structure (user classes)
• Java classes
• Function handle

All of the fundamental data types are shown in lowercase text in the diagram below. Additional data types
are user−defined, object−oriented.
You can create two-dimensional double and logical matrices using one of two storage formats: full or sparse.
For matrices with mostly zero valued elements, a sparse matrix requires a fraction of the storage space
required for an equivalent full matrix. Sparse matrices invoke methods especially tailored to solve sparse
problems.

IQRA Software All RIGHTS RESERVED 40


Numeric Data Types

Further more, numeric data type can be classified as follows.


• int8, uint8, int16, uint16, int32, uint32, int64, uint64
• single
• double
Numeric data types has signed and unsigned integers, single and double-precision floating-point numbers.
The double precision takes more memory than single and integer precision numbers.

Integer number

MATLAB supports four signed and four unsigned integer data types. Signed types means you can work with
negative and positive integers. But can not be represented in wide range.
Unsigned integers have a wider range of numbers, but these numbers can only be zero or positive i.e. no
negative.
MATLAB supports 1, 2, 3 and 8-byte storage for integer data. In this way you can save memory.
Example
If you want to store the 100, you can write as

x = int8(100)
It takes only 1-byte of memory to store the value of x.
But if you write

x = int16(100)
It takes 2-byte of memory to store the value of x.
Here is the range and data type.

Data Type Range Conversion Function


7 7
Signed 8-bit integer -2 to 2 - 1 int8
15 15
Signed 16-bit integer -2 to 2 -1 int16
31 31
Signed 32-bit integer -2 to 2 -1 int32
63 63
Signed 64-bit integer -2 to 2 -1 int64
8
Unsigned 8-bit integer 0 to 2 - 1 uint8
16
Unsigned 16-bit integer 0 to 2 -1 uint16
32
Unsigned 32-bit integer 0 to 2 -1 uint32
64
Unsigned 64-bit integer 0 to 2 -1 uint64

Table 10: MATLAB integer Data Type

IQRA Software All RIGHTS RESERVED 41


Floating-Point Number

The floating-point numbers can be represented in either double-precision or single-precision format. The
default is double precision, but you can convert into single precision number.
Any number stored as a double requires 64 bits and format as follows

Bit No 63 --- used for signed bit (0 = positive, 1 = negative)


Bit No 62 to 52 --- used to represent Exponent, biased by 1023
Bit No 51 to 0 --- used to represent fraction of number

The range of Double-Precision Values can be easily determined by the following


realmin(‘double’) to realmax(‘double’), returns

2.2251e-308 to 1.7977e+308
MATLAB creates the single data type for single precision.
Any number stored as a single requires 32 bits and format as follows
Bit No 31 --- used for signed bit (0 = positive, 1 = negative)
Bit No 30 to 23 --- used to represent Exponent, biased by 127
Bit No 22 to 0 --- used to represent fraction of number

The range of Single Precision Values can be easily determined by the following
realmin(‘single’) to realmax(‘single’), returns

1.1755e-038 to 3.4028e+038

MATLAB converts single and double Precision data from any data type as follows
x = int64(30)
y = double('x') converts double Precision data

y = single('x') converts single Precision data


MATLAB uses the special values inf, -inf, and NaN to represent values that are positive and negative infinity,
and not a number respectively.

Complex Numbers

Complex numbers consist of two separate parts: a real part and an imaginary part. The basic imaginary unit
is equal to the square root of -1. This is represented in MATLAB by either of two letters: i or j.
The variable x is assigned a complex number with a real part of 2 and an imaginary part of 3:
x = 2 + 3i;
Another way to create a complex number is using the complex function. This function combines two numeric
inputs into a complex output, making the first input real and the second imaginary:
x = ones(3) * 5;
y = rand(3) * -2;

IQRA Software All RIGHTS RESERVED 42


z = complex(x, y); returns
z=

5.0000 - 1.9003i 5.0000 - 0.9720i 5.0000 - 0.9129i


5.0000 - 0.4623i 5.0000 - 1.7826i 5.0000 - 0.0370i
5.0000 - 1.2137i 5.0000 - 1.5242i 5.0000 - 1.6428i

You can separate a complex number into its real and imaginary parts using the real and imag functions:
zr = real(z)
zr =
5 5 5
5 5 5
5 5 5

zi = imag(z)
zi =
-1.9003 -0.9720 -0.9129
-0.4623 -1.7826 -0.0370
-1.2137 -1.5242 -1.6428
Infinity and NaN

MATLAB uses the special values inf, -inf, and NaN to represent values that are positive and negative infinity,
and not a number respectively.

Infinity

MATLAB represents infinity by the special value inf. Infinity results from operations like division by zero and
overflow, which lead to results too large to represent as conventional floating-point values. MATLAB also
provides a function called inf that returns the IEEE arithmetic representation for positive infinity as a double
scalar value.
Example
x = 1/0 x = 1.e1000
x = Inf x = Inf
x = exp(1000) x = Iog(0)
x = lnf x = -Inf

Use the isinf function to verify that x is infinity:

x = log(0);
isinf(x) returns
ans = 1

IQRA Software All RIGHTS RESERVED 43


NaN

MATLAB represents values that are not real or complex numbers with a special value called NaN, which
stands for Not a Number. Expressions like 0/0 and inf/inf result in NaN, as do any arithmetic operations
involving a NaN.

Example, the statement n/0, where n is complex, returns NaN:

x = 7i/0
x = NaN + Infi

Use the isnan function to verify that x is NaN:

x = log(0);

isnan(x)

ans = 1

MATLAB also provides a function called NaN that returns the IEEE arithmetic representation for NaN as a
double scalar value:

x = NaN;

whos x

Name Size Bytes Class

x 1x1 8 double array

Logical Operations on NaN Because two NaNs are not equal to each other, logical operations involving
NaN always return false, except for a test for inequality, (NaN ~= NaN):

NaN > NaN

ans = 0

NaN ~= NaN

ans = 1

Identifying Numeric Types

You can check the data type of a variable x using any of these commands.

IQRA Software All RIGHTS RESERVED 44


Command Operation
whos x Display the data type of x
xType = class(x); Assign the data type of x to a variable.
isnumeric(x) Determine if x is a numeric type.
isa(x, 'integer') Determine if x is the specified numeric type.
(Examples for any integer, unsigned 64-bit integer,
isa(x, 'uint64') any floating point, double precision, and single
precision are shown here).
isa(x, 'float')

isa(x, 'double')

isa(x, 'single')
isreal(x) Determine if x is real or complex.
isnan(x) Determine if x is Not a Number (NaN).
isinf(x) Determine if x is infinite.
isfinite(x) Determine if x is finite.

Display Format for Numeric Values

By default, MATLAB displays numeric output as 5-digit scaled, fixed-point values. You can change the way
numeric values are displayed to any of the following:

• 5-digit scaled fixed point, floating point, or the best of the two

• 15-digit scaled fixed point, floating point, or the best of the two

• A ratio of small integers

• Hexadecimal (base 16)

• Bank notation

To change the numeric display setting, use either the format function or the Preferences dialog box
(accessible from the MATLAB File menu). The format function changes the display of numeric values for the
duration of a single MATLAB session, while your Preferences settings remain active from one session to the
next. These settings affect only how numbers are displayed, not how MATLAB computes or saves them.

Changing Format of data

Here are a few examples of the various formats and the output produced from the following two-element
vector x, with components of different magnitudes.

Check the current format setting:

get(0, 'format')

IQRA Software All RIGHTS RESERVED 45


ans = short

Set the value for x and display in 5-digit scaled fixed point:

x = [4/3 1.2345e-6]

x = 1.3333 0.0000

Set the format to 5-digit floating point:

format short e

x = 1.3333e+000 1.2345e-006

Set the format to 15-digit scaled fixed point:

format long

x = 1.33333333333333 0.00000123450000

Set the format to 'rational' for small integer ratio output:

format rational

x = 4/3 1/810045

Set an integer value for x and display it in hexadecimal (base 16) format:

format hex

x = uint32(876543210)

x = 343efcea

IQRA Software All RIGHTS RESERVED 46


MATLAB Graphics
MATLAB includes good tools for visualization such as basic 2-D plots and 3-D graphics with lighting and
color maps etc. MATLAB has a powerful set of graphics routines that enable you to visualize your data and
models. The focus for this topic will be on working with quantitative experimental or observational data rather
than analytic mathematical functions. Several methods for displaying data from vectors and matrices will be
covered, including various types of 2-D and 3-D plots.
Procedures for customizing displays from a point and click Property Editor and from the command line or
from a script using the Handle Graphics system will be explained as well. MATLAB basic analysis methods
for descriptive statistics and methods of sorting and restructuring data layout will be illustrated.

MATLAB provides a variety of techniques to display data graphically.


MATLAB plotting process of visualizing data typically involves a series of operations, which are as follows.

Creating and manipulating the Graph: MATLAB defines many graph types, such as line, bar, histogram,
pie graphs and 3-D graphs, such as surfaces, slice planes, and streamlines etc.

There are two basic ways to create graphs in MATLAB.

Create graphs using plotting tools: MATLAB has very good plotting tool i.e. plottools.
Suppose you want to graph the function y = sin(x) + sin(2*x);
Where x = 0:0.01:10;
If you type these commands, the variables x and y will be stored in MATLAB workspace.
Now type plottools
It opens a figure window, which will be having the following sub-windows
Figure palette: containing New Subplots, Variables, Annotations.

Property Editor – Figure: containing Figure Name, Colormap, Figure color, Export setup etc.

Plot Browser: contains how many variables are responsible to plot the graph and with respect to which
variable, Axes properties etc.
The plottools has the following features
• Select the variables, plot them by right clicking and selecting the options.
• 2D and 3D sub-plots are possible.
• The annotations can be drawn on the figure.
• The titles, labels, colors, axes limits can be written on the figure.
• More data can be added to the graph.
• Figure object properties can be changed.
• M-file can be generated for the figure.

IQRA Software All RIGHTS RESERVED 47


• The zoom, pan, rotate, data cursor, reset view can be possible.
• The plot type can be frequently changed as stem, line, bar, area, stem, stairs etc.
• Exporting and saving a graph into different format can be done.

Basic Plotting Functions: The important graphics functions will be discussed in this section.
The plot function has different forms based on the input arguments. Lot of input arguments can be provided
to plot function to give various shape and size of the graph.

Label, title and legend


Example
x = 0:pi/100:2*pi;
y = sin(x)+sin(2*x);
plot(x, y)

It plots the graph y verses x.


Add the label and title
xlabel('x = 0:2\pi')
ylabel('Sine (x)')
title('Plot of the multiple Sine Function','FontSize',10)

You can set the font size as 10 in title argument.


You can plot multiple sine waves with a single plot function call as follows
y2 = sin(x-0.25)+sin((2*x)-0.25);
y3 = sin(x-0.5)+sin((2*x)-0.5);
plot(x,y,x,y2,x,y3)

The legend command provides an easy way to identify the individual plots of y, y2 and y3.

legend('sin(x)+sin(2*x)','sin(x-0.25)+sin((2*x)-0.25)','sin(x-0.5)+sin((2*x)-0.5)')

Style options
You can specify the color, line styles, and markers to the graph as follows
plot(x,y,'color_style_marker')

Various line types, plot symbols and colors may be obtained with plot(x,y,s) where s is a character string
made from one element from any the following column:
b blue
g green
r red
c cyan
m magenta

IQRA Software All RIGHTS RESERVED 48


The hold command lets you to add plots to an existing graph. When you type
hold on

Type another plotting command, MATLAB does not replace the existing graph and adds the new data to the
current graph. It rescales the axes if required.

Axis control and zoom


Once the plot is generated, you can change the axes limits with axis command as follows.
Axis([xmin xmax ymin ymax])
Example
Axis([-5 10 3 23])
Axis(‘equal’) %sets equal axes on both axes
Axis(‘square’) %sets the default rectangular frame to a square
Axis(‘normal’) %resets the values to default on both axes
Axis(‘off’) %removes all settings on both axes
Axis([-5 10 -inf inf]) %sets the x axis to -5, 10 and leaves the y axis limits to be
set automatically.

Peak function creates a contour plot.


Figure function opens a new figure window and make it the current figure.

Clf function clears the figure window.

The subplot command lets you to display multiple plots in the same window.

Example
t = 0:pi/10:2*pi;
[X,Y,Z] = cylinder(cos(t));
subplot(2,2,1); mesh(X)
subplot(2,2,2); mesh(Y)
subplot(2,2,3); mesh(Z)
subplot(2,2,4); mesh(X,Y,Z)

IQRA Software All RIGHTS RESERVED 49


The first two arguments in subplot function indicate the number of rows and columns for subplots, the third
argument indicate the position of the graph.
Axes can be controlled by
axis([xmin xmax ymin ymax])

axis([xmin xmax ymin ymax zmin zmax])

Mesh and Surface Plots: A surface can be defined by the z-coordinates of points above a grid in the x-y
plane, using straight lines to connect adjacent points. The mesh and surf plotting functions display surfaces
in 3-D. mesh produces wireframe surfaces that color only the lines connecting the defining points. surf
displays both the connecting lines and the faces of the surface in color. It creates a shaded 3D surface.

Example
To plot a sinc function

[A,B] = meshgrid(-10:.5:10);
R = sqrt(A.^2 + B.^2);
C = sin(R)./R;
mesh(A,B,C,'EdgeColor','blue')

It produces a sinc function plot in 3D and a warning message “Warning: Divide by zero.”
To suppress the warning message, add eps to the following line
R = sqrt(A.^2 + B.^2) + eps;
Example
[X, Y] = meshgrid(-pi:pi/10:pi);
Z = sin (X) .* sin (Y);
subplot(2,1,2),mesh(Z);
subplot(2,1,1),surf(Z);

3D Graphing: MATLAB provides a variety of functions for displaying 3-D data (i.e., data containing x-, y-,
and z-coordinates). You can display the data as line plots (plot3)
th
or rectangular grids (mesh, surf). The built-in colormaps can be used to represents the 4 dimensions. You
can type help graph3d in the command window to get the complete list of functions available for 3-D
graphics. Here are the list of commonly used 3-D functions.
Plot3 plot curves in space
Stem3 creates discrete data plot in 3-D
Bar3 plot 3-D bar graph
Bar3h plot 3-D horizontal graph
Pie3 make 3-D pie chart
Comet3 make animated 3-D line plot

IQRA Software All RIGHTS RESERVED 50


Fill3 draw filled 3-D polygons
Contour3 make 3-D contour plots
Scatter3 make scatter plot in 3-D
Mesh draw 3-D mesh surfaces
Meshc draw 3-D mesh surfaces along with contours
Surf draw 3-D surface plot
Surfc draw 3-D surface plot along with contours
trimesh mesh plot with traingle
Trisurf surface plot with traingle
Slice draw a volumetric surface with slices
Waterfall draw a waterfall plot with 3-D data
Cylinder create a cylinder
Sphere create a sphere

3D line plots: The 3-D analog of the plot function is plot3. If x, y, and z are three vectors of the same length,
use the following function
plot3(x,y,z)
Example
t = 0:pi/50:10*pi;
plot3(sin(t),cos(t),t)
axis square; grid on

If the arguments to plot3 are matrices of the same size, MATLAB plots lines
obtained from the columns of X, Y, and Z.

Examples
1. meshgrid:
[X,Y] = meshgrid([-2:.1:2]);
Z = X.*exp(-X.^2-Y.^2);
plot3(X,Y,Z)

2. fill3:
X = [0 0 0 0;1 1 -1 1;1 -1 -1 -1];
Y = [0 0 0 0;3 3 3 3;4 4 4 4];
Z = [0 0 0 0;1 1 -1 -1;-1 1 1 -1];
Fill(X, Y, Z, rand(3,4))
View(110, 40)

IQRA Software All RIGHTS RESERVED 51


3. contour3
r = linspace(-3,3,50);
[x,y] = meshgrid(r,r);
z = -5./(1+x.^2+y.^2);
contour3(z)

4. surf
u = -5:0.2:5;
[X,Y] = meshgrid(u,u);
Z = cos(X).*cos(Y).*exp(-sqrt(X.^2+Y.^2)/4);
surf(X,Y,Z)

5. waterfall
x = linspace(-3,3,50);
y = x;
[x,y] = meshgrid(x,y);
z = -5./(1+x.^2+y.^2);
waterfall(z)
hidden off

IQRA Software All RIGHTS RESERVED 52


Handle Graphics

This is the MATLAB graphics system. It includes high-level commands for two-dimensional and three-
dimensional data visualization. It also includes low-level commands that allow you to fully customize the
appearance of graphics as well as to build complete Graphical User Interfaces on your MATLAB
applications. This class covers the basics of matlab graphics, including making 2D and 3D visualizations,
displaying and saving images, importing data into matlab, and using matlab handle graphics. It is a hands-
on class and is intended for beginning and intermediate matlab users.
Basically Handle Graphics is an object-oriented graphics system that provides the necessary components to
create computer graphics. It supports commands to create lines, text, meshes and polygons as well as
interactive devices such as menus, push-pull buttons, radio buttons and dialog boxes. Using Handle
Graphics, you can directly manipulate the lines, surfaces, and other graphics elements that MATLAB’s high-
level routines use to produce various types of graphs. You can use Handle Graphics from the MATLAB
command line to modify the graph or in M-files to create user defined graphics functions.
Simple 2-D or 3-D plots are the plots, MATLAB automatically creates with basic functionalities. But if you
want an extra control on your graph appearance, you have to learn the handle graphics.

Graphics Objects
Handle Graphics objects are the basic drawing elements used by MATLAB to display data and to create
graphical user interfaces (GUIs). An object has several instances and each instance is associated with a
unique identifier called a handle. Using this handle, you can change/modify the object properties.
A line is a graphics object. It has several properties like line style, color, thickness etc. Once the line has
been drawn, you can change any of its properties later. On graphics screen, you may have lot of graphics
objects, among those how you can particular hold the line to change its properties. You can get hold on line
only by its handle.
So, what is basically a handle? Here is the answer.
MATLAB assign a floating point number to every graphic object in figure window and it used this number as
an address or name for the object. This floating point number is called the handle of the object. Handle is a
unique identifier.

These objects are mentioned as follows

IQRA Software All RIGHTS RESERVED 53


Root

Figure

Uicontrol Axes Uimenu

Image Line Patch Surface Text Light

Graphics Object Hierarchy

It is important to know the hierarchy of object tree diagram for the following reasons.
• It shows that which object will be affected if you change a property value.
• It tells you at which level you can query for handles of which objects.
root object corresponds to computer screen and it has no parent object. It exists after starting MATLAB
program. It is parent of figure objects. Handle of rot object equals to zero.
figure is parent of axes, uicontrol’s, uimenu’s and uicontextmenu’s.
uicontrol and uimenu have no children.
axes is parent of text, line, light, surface, patch, rectangle and image objects.

The Root Object: At the top of the hierarchy is the Root object. It belongs to the computer screen. There is
only one Root object. You do not have to create the Root object; it exists when you start MATLAB. You can
set the values of Root properties to affect the graphic display.

The Figure Object: Figure objects are the individual windows on the Root screen where MATLAB used to
display the graphics. Number of figure windows can be created. There is no limit. The Figures is the child of
the Root.

The Uicontrol Object: The Uicontrol objects are user interface controls like Pop-up menus, editable text
boxes, check boxes, pushbuttons, sliders etc. When user presses these buttons, the callback routines are
executed. Uicontrol objects are children of Figures and are therefore independent of Axes objects.

The Uimenu Object: The Uimenu objects are pull-down menus that execute callback routines, when users
select an individual menu item. MATLAB places Uimenus on the Figure window menu bar. Uimenus are
children of Figures and are independent of Axes objects.

IQRA Software All RIGHTS RESERVED 54


The Axes Object: The Axes objects define a region in a Figure window and plot their children
within this region. Axes are children of Figures and are parents of Image, Light, Line, Patch, Surface, and
Text objects.
The Image Object: The MATLAB Image consists of a data matrix and can be viewed only at the default 2-
D view.

The Light Object: The Light objects define light sources that affect all objects within the Axes.

The Line Object: Line objects are the basic graphics primitives used to create most 2-D and some 3-D
plots. High-level functions plot, plot3, and contour (and others) create Line objects.

The Patch Object: Patch objects are filled polygons with edges. A single Patch can contain multiple faces,
each colored independently with solid or interpolated colors. fill, fill3, and contour3 create patch objects.

The Surface Object: Surface objects are 3-D representations of matrix data created by plotting the value of
each matrix element as a height above the x-y plane. The high-level function pcolor and the surf and mesh
group of functions create Surface objects.

The Text Object: Text objects are character strings. The coordinate system of the parent Axes positions
the Text. The high-level functions title, xlabel, ylabel, zlabel, and gtext create Text objects.

Object Properties
Every graphics object on figure has several properties associated with it.
For example, the properties of a line include type, parent, visible, color, linestyle, line width, xdata, ydata,
etc. Similarly, the property of a text object, such as xlable or title include type, parent, visible, color, font
name, font size, font Wight, string, ect. Once the handle of an object is known, you can see list of its
properties and their current value with the command get (handle).

Example for the properties of a line and their current value


t = linspace(0,pi/4,100);
hL = line(t, sin(t)); %create a line of vector t and handle hL
get(hL) % query the properties of line and its values
Color = [0 0 1]
EraseMode = normal
LineStyle = -
LineWidth = [0.5]
Marker = none
MarkerSize = [6]
MarkerEdgeColor = auto
MarkerFaceColor = none
XData = [ (1 by 100) double array]
YData = [ (1 by 100) double array]

IQRA Software All RIGHTS RESERVED 55


ZData = []
BeingDeleted = off
ButtonDownFcn =
Children = []
Clipping = on
CreateFcn =
DeleteFcn =
BusyAction = queue
HandleVisibility = on
HitTest = on
Interruptible = on
Parent = [152.045]
Selected = off
SelectionHighlight = on
Tag =
Type = line
UIContextMenu = []
UserData = []
Visible = on

There are some properties common to all graphics objects. These properties are: children, clipping, parent,
type, user data, and visible.

The set and get functions specify and retrieve the value of existing graphics object properties. They also
enable you to list possible values for properties that have a fixed set of values. (You can also use the
Property Editor to set many property values. The basic syntax for setting the value of a property on an
existing object is
set(object_handle,'PropertyName','NewPropertyValue')

To query the current value of a specific object's property, use a statement like
returned_value = get(object_handle,'PropertyName');
Property names are always quoted strings. Property values depend on the particular property.

GUIDE (MATLAB Graphical User Interface Development Environment)

Guide is the short form of Graphical User Interface development environment. It provides a set of tools for
creating user’s graphical user interfaces (GUIs).
Using the GUIDE Editor, you can lay out a GUI easily by clicking and dragging GUI components -such as
panels, buttons, text fields, sliders, menus into the layout area.
GUIDE automatically generates an M-file that controls the GUI operation. Using the M-file editor, you can
add code to the callbacks to perform the functions.
To start the GUIDE, enter guide command at the MATLAB prompt. It displays the GUIDE Quick Start dialog
on the screen as follows

IQRA Software All RIGHTS RESERVED 56


The left most side of the figure window is called the component palette, which is having push buttons, pop-
up menus, axes, radio buttons, check box etc. If you drag a push button into the layout area, it appears on
the layout area.
There are four types of guide templates.
• Blank GUI (Default)
• GUI with Uicontrols
• GUI with Axes and Menu
• Modal Question Dialog

At a time you can select only one template.


To run the GUI, select Run from the Tools menu or click the run button on the toolbar.
GUIDE stores a GUI in two file formats, which are generated at the first time you save or run the GUI:
• A FIG-file, with extension .fig, which contains a complete description of the GUI layout and the
components of the GUI: push buttons, menus, axes, and so on.
• An M-file, with extension .m, which contains the code that controls the GUI, including the callbacks
for its components.
The GUI M-file initializes the GUI, contains code to perform tasks before the GUI appears on the screen
such as creating data or graphics and contains the callback functions that are executed each time a user
clicks a GUI component.

IQRA Software All RIGHTS RESERVED 57


MATLAB Applications
MATLAB is a high performance language for technical computing. Computation, visualization, and
programming are integrated in an easy-to-use environment. It has lot of applications in different areas like
signal processing, image processing, communications, control system, fuzzy logic etc.

1. Linear Algebra
Solving a linear system:
It is very easy to solve the linear algebraic equations in MATLAB. Solving equations is a basic task for
scientific applications. Let us see how MATLAB make this task easy and pleasant.
Example
Consider the following set of equations.
-6x - 2y + 2z = 15
-3x + 4y - 3z = 13
2x + 4y - 7z = -9
Write the above equation in matrix form like [A] {x} = {b}
Where x is the vectors of unknown variables such as x, y and z. Arrange the unknown in vector x and
coefficients in matrix A.

x= x
y
z

the coefficients of matrix is


-6 -2 2
A = -3 4 -3
2 4 -7

and the known constant vector is

15
b = 13
-9

IQRA Software All RIGHTS RESERVED 58


Now the MATLAB is ready to solve this equation.

A = [-6 -2 2; -3 4 -3; 2 4 -7];


b = [15; 13; -9];
x = A \ b;
x=
-2.7273
2.7727
2.0909
Cross check the solution
c = A*x;
c=
15.0000
13.0000
-9.0000
Finding eigenvalues and eigenvectors:
Calculating the eigenvalues in scientific applications is another challenge.
The eigenvalue of a given matrix is given as
Av=‫ג‬v
Where A is an n * n matrix, v is n * 1 vector and ‫ ג‬is scalar. Any value of λ for which this equation has a
solution is known as an eigenvalue of the matrix A. It is sometimes also called the characteristic value. The
vector, v, which corresponds to this value, is called an eigenvector. The eigenvalue problem can be
rewritten as

Av-‫ג‬ v=0
Av-‫ג‬ v. I = 0
(A - ‫ג‬ . I).v = 0
where I is the identity matrix.
If v is non-zero, this equation will only have a solution if and only if

This equation is called the characteristic equation of A, and is an nth order polynomial in λ with n roots.
These roots are called the eigenvalues of A. We will only deal with the case of n distinct roots, though they
may be repeated. For each eigenvalue, there will be an eigenvector for which the eigenvalue equation is
true.
By hand finding a eigenvalue is a tough task, but in MATLAB it is very easy to find the eigenvalue.
Enter a matrix A and type [v, d] = eig(A)
A = [5 1 2;-3 5 4;4 2 1];
[v, d] = eig(A)

The eigenvector of matrix A is

IQRA Software All RIGHTS RESERVED 59


v=
0.1606 0.8018 0.8117
0.5840 -0.2673 -0.1116
-0.7957 0.5345 0.5732

The eigenvalue of matrix A is


d=
-1.2749 0 0
0 6.0000 0
0 0 6.2749

Matrix factorizations:
MATLAB provides the built-in functions for matrix factorization (de-composition). There are several methods
to factorize the matrix.
LU method: The function name is lu. To get the LU factorization of a square matrix A, type the command,
[L,U] = lu(A)

MATLAB returns the lower triangular matrix L and upper triangular matrix U,
so that L*U = A.
Let matrix
A = [5 1 2;-3 5 4;4 2 1];
[L,U] = lu(A)
L=
1.0000 0 0
-0.6000 1.0000 0
0.8000 0.2143 1.0000
U=
5.0000 1.0000 2.0000
0 5.6000 5.2000
0 0 -1.7143

L*U =
5.0000 1.0000 2.0000
-3.0000 5.0000 4.0000
4.0000 2.0000 1.0000
Interpolation:
Interpolation is a technique of finding a functional relationship between variables such that a given set of
data points (discrete values) of the variable satisfy that relationship. Suppose you have a set of data points.
When you want to pass a smooth curve through these points, the curve may not be completely smooth. You
need some more number of points between data sets. So finding of intermediate points between a given
data sets is called the interpolation.
MATLAB provides the following functions for interpolation.

IQRA Software All RIGHTS RESERVED 60


ynew = interp1(x, y, xnew, method) %for 1-D interpolation
znew = interp2(x, y, z, xnew, ynew, method) %for 2-D interpolation
vnew = interp3(x, y, z, v, xnew, ynew, znew, method) %for 3-D interpolation
Where method is optional argument, it is nothing but the method of interpolation that you want to use. There
are four choices for methods
nearest, linear, cubic and spline.
The default is linear. The smoothness of data depends upon the choice you want to select.
The below is the MATLAB program.

x = [0 0.785 1.570 2.356 3.141 3.927 4.712 5.497 6.283];


y = [0 0.707 1.000 0.707 0.000 -0.707 -1.000 -0.707 0.000];
xi = linspace(0,pi,50);
yi = interp1(x, y, xi, 'nearest');
subplot(2,2,1); plot(xi, yi); title('Nearest Interpolation')
yi = interp1(x, y, xi, 'linear');
subplot(2,2,2); plot(xi, yi); title('Linear Interpolation')
yi = interp1(x, y, xi, 'cubic');
subplot(2,2,3); plot(xi, yi); title('Cubic Interpolation')
yi = interp1(x, y, xi, 'spline');
subplot(2,2,4); plot(xi, yi); title('Spline Interpolation')

IQRA Software All RIGHTS RESERVED 61


In the above figure, you can see the smoothness of the data set. The spline interpolation method provides
better smoothness than other methods.
Remember that in all interpolation functions, it is required that the input data points in x be monotonocally
either increasing or decreasing.

Double integrals:
The double integral can be termed as

∫ ∫ f (x, y) dx dy
st nd
The limits of 1 integral is a to b and 2 is c to d.

MATLAB provides a function dblquad for double integration; it used to be called quad2. The calling syntax
for dblquad is:

Integral = dblquad (‘ function_name,’ c, d , a , b, tol, method)


Where tol and method are optional input arguments. The order of integration limited in the input argument
list is important – the inner integral limits c and d come first in the list, the outer limits a and b comes next.
The optional argument tol specifies a choice that the user makes about the method of integration to be used,
e.g., quad or quad8. the default method is quad. Since the double integrals are perfumed by carrying out 1-
D integrals in one direction while holding the other variable constant and then repeating the procedures in
the second directions, both quad and quad8 are valid choices for the method.
Example
Calculate the double integral below.

In MATLAB, make function file integrand2.m and save the following code
function z=integrand2(x,y)
z=sqrt(exp(x)).*sqrt(exp(y));

Now call the inbuilt-in function to find the double integral


I2=dblquad('Integrand2',0,1,0,1)

I2 =
1.6834
We will now take a look of the integrated area.

[X,Y]=meshgrid(0:0.1:1,0:0.1:1); % Makes a grid of calculation points.


Z=Integrand2(X,Y); % Calculates the integral.

IQRA Software All RIGHTS RESERVED 62


mesh(X,Y,Z) ; % Makes a plot that connects these points.

The last three lines achieve Figure below.

Ordinary Differential Equations:


There is a separate suite of ODE solver in MATLAB. There are various additional built-in functions for ODE
solutions like ode23, ode45. The versatility comes with a cost, the more you want from these functions; the
more you have to understand about its complex input structure.
th th
The function ode23 and ode45 are implementations of 2nd / 3rd order and 4 / 5 order Runge-kutta
methods respectively.
[time, solution] = ode23(‘function_name’, tspan, x0)

Example
st
Solve the 1 order linear differential equation
dx =x+t
dt
with initial condition x(0) = 0.
Write a function to compute the new derivatives
function xdot = simpode(t, x); %simpode computes xdot = x + t
xdot = x + t;

IQRA Software All RIGHTS RESERVED 63


save this file as simpode.m

Now use the ode23 and ode45 to compute the solution


tspan = [0 2];
x0 = 0;
[t, x] = ode23('simpode', tspan, x0);
plot (t, x)
xlabel('t'), ylabel('x')

The below figure shows the numerical solution of the equation using ode23.

IQRA Software All RIGHTS RESERVED 64


LAB MANUAL

IQRA Software All RIGHTS RESERVED 65


CHAPTER – 1
INTRODUCTION TO MATLAB

Choose the correct one:

1. Which of the following is a correct comment?


1. */ Comments */
2. // Comment
3. % Comment
4. { Comment }

2. Which of the following is used to clear the command window?


1. clf
2. clear
3. clc
4. cls

3. Which of the following shows the working directory?


1. dir
2. ls
3. pwd
4. All of above.

4. Which of the following is used to know the version of MATLAB?


1. more
2. ver
3. home
4. version

5. Which of the following MATLAB window is used to store all the variables?
1. command window
2. command history window
3. workspace window
4. None of above

6. The basic building block of MATLAB is


1. array
2. structure

IQRA Software All RIGHTS RESERVED 66


3. toolbox
4. matrix

7. The fundamental data type in MATLAB is


5. array
6. structure
7. toolbox
8. matrix

8. The output of the following program is


A = [9 10 2;-3 5 4;4 2 1];
A(1,:) = [1, -5, 0]
A=

Ans: _______________________________

9. The output of the following program is


t = 1:10;
x = t.*sin(t);
y = (t-1)./(t+1);
x=
y=

Ans: _______________________________

10. . The output of the following program is


A = [1 2 3;2 4 6;5 7 9];
A(:,2:3) = [ ];
A=

Ans: _______________________________

11. The output of the following program is


A = [0 2 3;2 -4 0;0 0 9];
x = find(A);
x=

IQRA Software All RIGHTS RESERVED 67


Ans: _______________________________

12. The output of the following program is


A = [1 2 0;2 -4 6;5 0 9];
all(A) =
any(A) =

Ans: _______________________________

Compute the following


5 5
1. 3 /(3 - 1)
2
2. 5*[(√5 - 1) / (√5 + 1) ] – 1
3. sin(π/6), cos(π/12), tan(2*π/5)
2 2
4. y = cosh (x) – sinh (x) with x = 32 π
3 5
5. log10(e ) + log10(10 )
14
6. e and (382801)π to 15 digits each. Which is bigger?
7. Compute to 15 digits: cosh(0.1)

Remarks: _____________________________

IQRA Software All RIGHTS RESERVED 68


CHAPTER – 2
MATLAB COMPUTATION

Choose the correct one:

1. The function eye(3) produces


1. 1 by 1 vector
2. 3 by 3 matrix
3. 3 by 3 identity matrix
4. None of above

2. The output of the following is


a =[3 7 6 4;9 4 10 2;1 8 3 5];
a(end, 2)
1. 10
2. 8
3. 6
4. 3

3. The screen output can be suppressed by


1. . operator
2. ^ operator
3. : operator
4. ; operator

4. All MATLAB commands and expression are entered in


1. MATLAB window
2. command window
3. workspace window
4. None of above

5. The output of the following is


A=[1 4 3;4 9 6;7 8 4];
A + A’ =
1. 2 8 6
8 18 12
14 16 8
2. 1 4 7

IQRA Software All RIGHTS RESERVED 69


4 9 8
3 6 4
3. 4 9 8
1 4 7
3 6 4
4. All of above

6. What is the result of the following commands?


a = [2 1 3];
b = [-1 -2 -3];
conv(a,b)

Ans: _______________________________

7. What is the result of each of the following commands?


a = [1+j, 1+2*j, 3, 4, 5*j];
k = find(imag(a)==0);
a(k)

Ans: _______________________________

8. What is the result of each of the following commands?


a = [zeros(3); ones(1,3)]
b = [zeros(3); ones(3,1)]

Ans: _______________________________

9. What are all the results of the following commands?


a = [3 4; 7 8];
b = [1 0; 0 1];
a'
a-1
a .* b
a*b

IQRA Software All RIGHTS RESERVED 70


a|b
a&b
a .^ 2
a^2

Ans: _______________________________

10. What are all the results of the following commands for a given matrix?
a = [9 4 7 2;1 6 3 5;3 10 6 4]
a(2, 3)
a(0, 2)
a(5)
a’
a(:, [2 2 2])
a(1:2:end, 1:2:end)
a(end:-1:1, :)
max(a)
b = a; b([2 3],[1 4]) = [11 22; 33 44]; b
b = a; b(:,2) = [ ]; b
log10([1 10 100 0.1])

Ans: _______________________________

11. Write any correct MATLAB code to create a matrix N that should be a 5 * 5 array of zeros with
a 1 in the middle.

12. Let P be a vector. Write any correct MATLAB code to change all the 1’s in P to be 2’s. That is
if P starts off as [0 1 4 1 3.3], then it should become [0 2 4 2 3.3].

13. Give an example of a symmetric matrix of size 4x4 with elements that are all non-zero and
are as different from each other as possible.

14. Give an example of a diagonally dominant matrix of size 4x4 with elements that are all non-
zero.

IQRA Software All RIGHTS RESERVED 71


15. Clear all variables. Define the matrix: A = [1:4; 5:8; 1 1 1 1]. Predict and check the result of
the following.
x = A(:, 3)
B = A(1 : 3, 2 : 2)
A(1, 1) = 9 + A(2, 3)
A(2 : 3, 1 : 3) = [0 0 0; 0 0 0]
A(2 : 3, 1 : 2) = [1 1; 3 3]
y = A(3 : 3, 1 : 4)
A = [A; 2 1 7 7; 7 7 4 5]
C = A([1, 3], 2)
D = A([2, 3, 5], [1, 3, 4])
D(2, :) = [ ]

16. Define the matrices: T = [3 4; 1 8; -4 3]; A = [diag(-1:2:3) T; -4 4 1 2 1]; Perform the following
operations on the matrix A:
Extract a vector consisting of the 2nd and 4th elements of the 3rd row.
Find the minimum of the 3rd column.
Find the maximum of the 2nd row.
Compute the sum of the 2nd column.
Compute the mean of the 1st and 4th rows.
Extract the submatrix consisting of the 1st and 3rd rows and all columns.
Extract the submatrix consisting of the 1st and 2nd rows and the 3rd, 4th and 5th
columns.
Compute the total sum of the 1st and 2nd rows
Add 3 to all elements of the 2nd and 3rd columns

17. Let A = [2 4 1; 6 7 2; 3 5 9]. Provide the commands which:


Assign the first row of A to a vector x
Assign the last 2 rows of A to a vector y
Add up the columns of A
Add up the rows of A
Compute the standard error of the mean of each column of A (i.e. the standard
deviation divided by the square root of the number of elements used to
compute the mean)

Remarks: _____________________________

IQRA Software All RIGHTS RESERVED 72


CHAPTER – 3
PROGRAMMING IN MATLAB

Choose the correct one:

1. When each element in a vector or matrix is to be processed, which of the following control
construct is used?
1. while loop
2. if-else ladder
3. for loop
4. None of above

2. You can find lot of variables stored in MATLAB workspace after executing a
1. dat file
2. function file
3. script file
4. All of above

3. What is the result of the following commands?


a = [ ];
for k = 5:-1:2
a = [a, k];
end
a=
1. [4 3]
2. [4 3 2]
3. [5 4 3 2]
4. [4 3 2 1]

4. What are the results of the following commands?


a = [5 2 3 5 8];
b = [9 2 5 0 8];
a == 5
a == b

1. [1 0 0 1 0] & [0 1 0 0 1]
2. [1 1 0 0 0] & [0 0 1 0 1]
3. [1 0 1 1 0] & [0 1 0 1 1]
4. None of above

IQRA Software All RIGHTS RESERVED 73


5. The first word in function definition line must be
1. Function [ a, b] = abc(x, y)
2. function [ a, b] = abc(x, y)
3. FUNCTION [ a, b] = abc(x, y)
4. All of above

6. The file kase.m contains the following:


y = 5;
x = 6;
z = x + y;
The file grape.m contains the following:
function z = grape(x,y)
z = x + y;
(i) What is the result of the following commands?
clear
x = 2;
y = 5;
kase
z

Ans: _______________________________

(ii) What is the result of the following commands?


clear
x = 2;
y = 5;
z = grape(x,y);
z

Ans: _______________________________

IQRA Software All RIGHTS RESERVED 74


7. What is the output of the following statements?
for i =1:1:3
a(i,i)=0;
end
for i=1:1:3
a(i,i)=a(i,i)+i*2;
end
a(3,3) =

Ans: _______________________________

8. What is the output of the following statements?


for i =1:1:3
a(i,i)=0;
end
for i=1:1:3
a(i,i)=2*a(i,i)+i;
end
a(3, 3) =

Ans: _______________________________

9. The following is the function named foo


function y = foo(x)
z = 2*x;
y = 2*z
z=y-4

What are the values returned from the following function calls

(i) foo(10) (ii) foo(foo(2))

Ans: _______________________________

IQRA Software All RIGHTS RESERVED 75


10. What is the output of the following statements?
N = 5;
k = -N:N;
x = sin(k*pi/N);
y = cos(k*pi/N);
fill(x,y,'g')
axis square

Ans: _______________________________

11. Let A = [2 7 9 7; 3 1 5 6; 8 1 2 5]. Explain the results or perform the following commands:
A’
A(1, :)’
A(:, [14])
A([23], [31])
reshape (A, 2, 6)
A(:)
flipud (A)
fliplr (A)
[A A(end, :)]
[A; A(1 : 2, :)]
sum (A)
sum (A’)
mean (A)
mean (A’)
sum (A, 2)
mean (A, 2)
min (A)
max (A’)
min (A(:, 4))
[min(A)’ max(A)’]

Ans: _______________________________

IQRA Software All RIGHTS RESERVED 76


12. Let x = [3 -1 4 2 7 2 3 5 4] Explain the results or perform the following commands:
y = x < 4, x(y)
x(y(y))

13. Plot the function y = sin(x) + x − x cos(x) in two separate figures for the intervals: 0 < x < 30
and −100 < x < 100. Add a title and axes description.

3 2
14. Plot the functions f(x) = x, g(x) = x , h(x) = ex and z(x) = ex over the interval [0, 4] on the
normal scale and on the log-log scale. Use an appropriate sampling to get smooth curves.
Describe your plots by using the functions: xlabel, ylabel, title and legend.

15. Make a plot of the functions: f(x) = sin(1/x) and f(x) = cos(1/x) over the interval [0.01, 0.1].
How do you create x so that the plots look good?

16. Let x = [1 5 2 8 9 0 1] and y = [5 2 2 6 0 0 2]. Execute and explain the results of the following
commands:
x>y
y<x
x == y
x <= y
y >= x
x|y
x & (~y)
(x > y) | (y < x)
(x > y) & (y < x)

17. Let x = 1:10 and y = [3 5 6 1 8 2 9 4 0 7]. The exercises here show the techniques of logical-
indexing.
Execute and interpret the results of the following commands:
(x > 3) & (x < 8)
x (x > 5)
y (x <= 4)
x ((x < 2) | (x >= 8))
y ((x < 2) | (x >= 8))
x (y < 0)

IQRA Software All RIGHTS RESERVED 77


18. Determine the sum of the first 50 squared numbers with a control loop.

19. Write the script cubic roots that for given a, b and c returns the roots of the cubic equation: a
x2+b x+c = 0.

20. The area of a triangle with sides of length a, b, and c is given by:
ar = √ (s − a) (s − b) (s − c), where s = (a + b + c)/2. Write a function that accepts a, b and c as
inputs and returns the value ar as output.
Note that the sides should be non-negative and should fulfill the triangle inequality. Make use of
the error command.

21. The Fibonacci numbers are computed according to the following relation:
FN = FN – 1 + FN – 2 with F0 = F1 = 1
Compute the first 10 Fibonacci numbers.

22. Solve (symbolically) the system of linear equations

3x + 4y + 5z = 2
2x - 3y + 7z = -1
x - 6y + z = 3
Check your answer using matrix multiplication.

4 4
23. Factor the polynomial x − y .

24. Find the derivatives of the following functions


3 2
(i) f (x) = 6x − 5x + 2x − 3
(ii) f (x) = sin(3x 2 + 2)

IQRA Software All RIGHTS RESERVED 78


CHAPTER – 4
MATLAB DATA TYPES

Choose the correct one:

1. MATLAB supports how many fundamental data types


1. 10
2. 15
3. 18
4. 8

2. If you get the Out of Memory message from MATLAB, which of the following
command to free up the memory?
1. free
2. pack
3. quit
4. save

3. If MATLAB application needs to store a large amount of data, for speed and less memory
usage you need to use
1. structure of arrays
2. arrays of structure
3. sparse matrices
4. All of above

4. The performance in MATLAB can be measured by


1. tic, toc
2. profile
3. All of above
4. None of above

5. The default floating-point numbers can be represented as


5. double -precision format
6. single-precision format
7. All of above
8. None of above

6. Write a short code that will plot a sinusoid of frequency 50 Hz for 10 cycles.

IQRA Software All RIGHTS RESERVED 79


7. Write a MATLAB code fragment to generate the following figure, including axis labels, and title.

Remarks: _____________________________

IQRA Software All RIGHTS RESERVED 80


CHAPTER – 5
MATLAB GRAPHICS

Choose the correct one:

1. The MATLAB graphics command hold on is used


1. to hold the current graph and plot another graph on it
2. to hold the previous graph and plot another graph on it
3. to hold the current graph
4. to plot another graph on it

2. Which of the following action can be performed on figure window?


1. zooming in and zooming out
2. panning
3. generating M-Code to reproduce the figure
4. All of the above

3. A callback is a sequence of commands that are execute when


1. a graphics object is active
2. some calculation and processing are performed
3. setting are done for relevant object properties
4. getting necessary information / values

4. The MATLAB GUIDE is


1. MATLAB Graphics User Interface Design Environment
2. stores GUIs in file (.m file), which is generated the first time you save or run the
GUI
3. stores GUIs in file (.fig file), which is generated the first time you save or run the
GUI
4. All of above

5. The Basic Graphics contain


1. 2-D plotting
2. The Figure Window
3. Images
4. All of above

6. Handle Graphics is
1. used to extra control on your graph
2. used to provide handle of object
3. used to control the properties of object
4. All of above

IQRA Software All RIGHTS RESERVED 81


7. In the object hierarchy, the child of AXES is
1. Figure
2. Text
3. Uimenus
4. Uicontrols
8. Make two graphs in the same figure to plot the following two functions:
2
f(t) = 3t + 2t – 0.5
g(t) = 2t cos(t)
Where the variable t varies from 0 to 10 with step 0.5
Graph 1: f and g versus t
Draw f in blue 0, and g in red *.
Give title to your graph and label the axes.
Graph 2: g versus f
- Draw the plot using blue line.
- Give title to your graph and label the axes.

9. Plot the following functions


f(x) = x
3
g(x) = x
x
h(x) = e
x + sin(x)
z(x) = e
plot over the interval [0, 4] on the normal scale and on the log-log scale using subplot. Use an
appropriate sampling to get smooth curves.
Describe your plots by using the functions: xlabel, ylabel, title and legend.

10. Plot the function y = sin(x) + x − x cos(x) in two separate figures for the intervals:
0 < x < 30 and −100 < x < 100. Add a title and axes description.

11. Plot the following functions in one figure


y1 = sin(3*x);
y2 = cos(5*x);
y3 = sin(3*x).*cos(5*x);
Use interval [0, 10]. Use legend, text, xlabel, ylabel, axes.

12. Plot the real part and imaginary part of the following signal
x(t) = exp(0.5t + j(t+π/3))
Use interval [0, 10].

IQRA Software All RIGHTS RESERVED 82


CHAPTER – 6
MATLAB APPLICATIONS

Choose the correct one:

1. Which of the following method is used for matrix factorization


1. Range Kutta method
2. Least square method
3. Cholesky method
4. None of above

2. Solve the equations


2x − y + z = 4
x+y+z=3
3x − y − z = 1
using the left division operator. Also compute the determinant (det) and the condition estimator
(rcond).

3. Find the eigenvalues and eigenvector of the following matrix


A = [6 9 2;-7 5 8;7 2 11];

Remarks: _____________________________

IQRA Software All RIGHTS RESERVED 83


Appendix

Preliminaries:
Below you find a few basic definitions on computers and programming. Please get acquainted
with them since they introduce key concepts needed in the coming sections:
• A bit (short for binary digit) is the smallest unit of information on a computer. A single bit
can hold only one of two values: 0 or 1. More meaningful information is obtained by
combining consecutive bits into larger units, such as byte.
• A byte - a unit of 8 bits, being capable of holding a single character. Large amounts of
memory are indicated in terms of kilobytes (1024 bytes), megabytes (1024 kilobytes), and
gigabytes (1024 megabytes).
• Binary system - a number system that has two unique digits: 0 and 1. Computers are
based on such a system, because of its electrical nature (charged versus uncharged).
Each digit position represents a different power of 2. The powers of 2 increase while
0
moving from the right most to the left most position, starting from 2 = 1. Here is an
example of a binary number and its representation in the decimal system:
4 3 2 1 0
10110 = 1*2 + 0*2 + 1*2 + 1*2 + 0*2 = 16 + 0 + 4 + 2 + 0 = 24
• Data is information represented with symbols, e.g. numbers, words, signals or images.
• A command is an instruction to do a specific task.
• An algorithm is a sequence of instructions for the solution of a specific task in a finite
number of steps.
• A program is the implementation of an algorithm suitable for execution by a computer.
• A variable is a container that can hold a value. For example, in the expression: x+y, x and
y are variables. They can represent numeric values, like 25.5, characters, like ’c’ or
character strings, like MATLAB. Variables make programs more flexible. When a
program is executed, the variables are then replaced with real data. That is why the same
program can process different sets of data.
Every variable has a name (called the variable name) and a data type. A
variable’s data type indicates the sort of value that the variable represents.
• A constant is a value that never changes. That makes it the opposite of a variable. It can
be a numeric value, a character or a string.
• A data type is a classification of a particular type of information. The most basic data
types are:
• integer: a whole number; a number that has no fractional part, e.g. 3.
• floating-point: a number with a decimal point, e.g. 3.5 or 1.2e-16.
• character: readable text character, e.g. ’p’.

IQRA Software All RIGHTS RESERVED 84


• A bug is an error in a program, causing the program to stop running, not to run at all or to
provide wrong results. Some bugs can be very subtle and hard to find. The process of
finding and removing bugs is called debugging.
• A file is a collection of data or information that has a name, stored in a computer. There
are many different types of files: data files, program files, text files etc.
• An ASCII file is a standardized, readable and editable plain text file.
• A binary file is a file stored in a format, which is computer-readable but not human-
readable. Most numeric data and all executable programs are stored in binary files.
MATLAB binary files are those with the extension ’.mat’.

Command Result
n = rank(A) n becomes the rank of matrix A
x = det(A) x becomes the determinant of matrix A
x = size(A) x becomes a row-vector with 2 elements: the number of rows and columns
of A
x = trace(A) x becomes the trace (sum of diagonal elements) of matrix A
x = norm(v) x becomes the Euclidean length of vector v
C=A+B sum of two matrices
C=A-B subtraction of two matrices
C=A*B multiplication of two matrices
C = A .* B ’element-by-element’ multiplication (A and B are of equal size)
-1
C=A^k power of a matrix (k Є Z; can also be used for A )
C = A .^ k ’element-by-element’ power of a matrix
T
C = A’ the transposed of a matrix; A
C = A ./ B ’element-by-element’ division (A and B are of equal size)
X=A\B finds solution in least squares sense to system of equations AX = B
X=B/A finds the solution of XA = B, analogous to the previous command
C = inv(A) C becomes the inverse of A
C = null(A) C is an orthonormal basis for the null space of A obtained from the singular
value decomposition
C = orth(A) C is an orthonormal basis for the range of A
C = rref(A) C is the reduced row echelon form of A
L = eig(A) L is a vector containing the eigenvalues of a square matrix A
[X,D] = eig(A) produces a diagonal matrix D of eigenvalues and a full matrix X whose
columns are the corresponding eigenvectors of A
S = svd(A) S is a vector containing the singular values of A

IQRA Software All RIGHTS RESERVED 85


[U,S,V] = svd(A) S is a diagonal matrix with nonnegative diagonal elements in decreasing
order; columns of U and V are containing singular vectors
x = linspace(a,b,n) generates a vector x of n equally spaced points between a and b
a b
x = logspace(a,b,n) generates a vector x starting at 10 and ended at 10 containing n values
A = eye(n) A is an n × n identity matrix
A = zeros(n,m) A is an n × m matrix with zeros (default m = n)
A = ones(n,m) A is an n × m matrix with ones (default m = n)
A = diag(v) gives a diagonal matrix with the elements v1, v2, . ., vn on the diagonal
X = tril(A) X is lower triangular part of A
X = triu(A) X is upper triangular part of A
A = rand(n,m) A is an n × m matrix with elements uniformly distributed between 0 & 1
A = randn(n,m) ditto - with elements standard normal distributed
v = max(A) v is a vector with the maximum value of the elements in each column of A
or v is the maximum of all elements if A is a vector
v = min(A) ditto - with minimum
v = sum(A) ditto - with sum
grid on/off adds a grid to the plot at the tick marks or removes it
axis([xmin xmax sets the minimum and maximum values of the axes
ymin ymax])
box off/on removes the axes box or shows it
xlabel(’text’) plots the label text on the x axis
ylabel(’text’) plots the label text on the y axis
title(’text’) plots a title above the graph
text(x,y,’text’) adds text at the point (x,y)
gtext(’text’) adds text at a manually (with a mouse) indicated point
legend(’fun1’,’fun2’) plots a legend box (move it with your mouse) to name functions
legend off deletes the legend box
clf clear the current figure
subplot create a subplot in the current figure
Table : Frequently used matrix operations and functions.

IQRA Software All RIGHTS RESERVED 86


Table of Contents

1. Introduction To Simulink........................................................................ 88
2. How Simulink works ............................................................................. 94
3. Simulink basics ..................................................................................... 98
4. Subsystem & Masking ........................................................................ 104
5. Simulink Debugger .............................................................................. 111
6. Simulink Applications .......................................................................... 115
7. Lab Manual ......................................................................................... 120

IQRA Software All RIGHTS RESERVED 87


Introduction to Simulink
Simulink is an extension to MATLAB for the modeling and simulation of mathematical systems. In Simulink,
systems are drawn on screen as block diagrams. Many elements of block diagrams are available (such as
transfer functions, summing junctions, etc.), as well as virtual input devices (such as function generators)
and output devices (such as oscilloscopes). Simulink is integrated with MATLAB and data can be easily
transferred between the programs. In this tutorial, we will introduce the basics of using Simulink to model
and simulate a system.
It is a software package for modeling, simulating, and analyzing dynamic systems. It supports linear and
nonlinear systems, modeled in continuous time, sampled time, or a hybrid of the two. Simulations are much
interactive; you can change parameters and immediately see the results.
Simulink is a graphical representation of systems, differential equations, or problems encountered in
engineering fields. Blocks can be assembled to reproduce almost anything as long as it can be modeled
mathematically. Simulink has become an important part of aeronautical, computer, electrical, and
mechanical engineering programs and industries.
Simulink provides a graphical user interface (GUI) for building models as block diagrams, using click-and-
drag mouse operations. It contains a comprehensive block library of sinks, sources, linear and nonlinear
components, and connectors. You can also customize and create your own blocks by writing S-function.
Simulink can be used to control the systems with the correct hardware and software. The electronic
equipment manufacturers such as Texas Instruments, Motorola and Analog devices etc. create circuit
boards for integration with a PC running Simulink model. The output can be directly saved to a computer
and analyzed to improve the performance of the model or write the report, more efficiently than in the past.
A goal of Simulink is to give you a sense of the modeling and simulation, through an environment that
encourages you to analyze a question, model it, and see what happens.
All Simulink operations should be done in Simulink windows.

Getting Started with Simulink

Simulink can be started from the MATLAB command prompt by entering the following command:
simulink
Or
You can click on the "Simulink Library Browser" button at the top of the MATLAB command window as
shown below:

IQRA Software All RIGHTS RESERVED 88


IQRA Software All RIGHTS RESERVED 89
The Simulink Library Browser window now appears on the screen. Most of the blocks needed for modeling
basic systems can be found in the subfolders of the main "Simulink" folder (opened by clicking on the "+" in
front of "Simulink"). Once the "Simulink" folder has been opened, the Library Browser window should look
like:
On Windows platforms, you can display the Simulink library window by right-clicking the Simulink node in the
Simulink Library Browser window.
On UNIX platforms, starting Simulink displays the Simulink block library window.

Basic Elements

There are two major classes of elements in Simulink: blocks and lines. Blocks are used to generate,
modify, combine, output, and display signals. Lines are used to connect the blocks and transfer signals from
one block to another.

Blocks

The subfolders underneath the "Simulink" folder indicate the general classes of blocks available in simulink
library to use:

The descriptions of basic blocks are as follows.


• Continuous: Linear, continuous-time system elements (integrators, transfer functions, state-space
models, etc.).
• Discrete: Linear, discrete-time system elements (integrators, transfer functions, state-space
models, etc.).
• Functions & Tables: User-defined functions and tables for interpolating function values.
• Math: Mathematical operators (sum, gain, dot product, etc.).
• Nonlinear: Nonlinear operators (coulomb/viscous friction, switches, relays, etc.).
• Signals & Systems: Blocks for controlling/monitoring signal(s) and for creating subsystems.

IQRA Software All RIGHTS RESERVED 90


• Sinks: Used to output or display signals (displays, scopes, graphs, etc.).
• Sources: Used to generate various signals (step, ramp, sinusoidal, etc.).

Blocks have zero to several input terminals and zero to several output terminals. Unused input terminals are
indicated by a small open triangle. Unused output terminals are indicated by a small triangular point. The
block shown below has an unused input terminal on the left and an unused output terminal on the right.

Lines

Lines are used to connect the various bocks and transmit signals in the direction indicated by the arrow.
Lines must always transmit signals from the output terminal of one block to the input terminal of another
block. One exception to this is that a line can tap off of another line. This sends the original signal to each of
two (or more) destination blocks, as shown below:

Lines can never inject a signal into another line; lines must be combined through the use of a block such as
a summing junction.

A signal can be either a scalar signal or a vector signal. For Single-Input, Single-Output systems, scalar
signals are generally used. For Multi-Input, Multi-Output systems, vector signals are often used, consisting
of two or more scalar signals. The lines used to transmit scalar and vector signals are identical. The type of
signal carried by a line is determined by the blocks on either end of the line.

Building a Model

To demonstrate how a system is represented using Simulink, we will build the block diagram for a simple
model consisting of a sinusoidal input multiplied by a constant gain, which is shown below:

IQRA Software All RIGHTS RESERVED 91


This model consists of three blocks: Signal Generator, Gain, and Scope. The Signal Generator is a Source
Block from which a sinusoidal input signal originates. This signal is transferred through a line in the
direction indicated by the arrow to the Gain Math Block. The Gain block modifies its input signal (multiplies
it by a constant value) and outputs a new signal through a line to the Scope block. The Scope is a Sink
Block used to display a signal (like an oscilloscope). We begin building our system by bringing up a new
model window in which to create the block diagram. This is done by clicking on the "New Model" button in
the toolbar of the Simulink Library Browser (looks like a blank page).

Building the system model is then accomplished through a series of steps:


1) The necessary blocks are gathered from the Library Browser and placed in the model window.
2) The parameters of the blocks are then modified to correspond with the system we are modelling.
3) Finally, the blocks are connected with lines to complete the model.

Each of these steps will be explained in detail using our example system. Once a system is built,
simulations are run to analyze its behavior.

Setting Preferences

Select Preferences from the Simulink File menu, MATLAB Preferences dialog box will be opened and you
can set the required preference.

IQRA Software All RIGHTS RESERVED 92


In this window, you can set the Simulink preferences like fonts and simulation etc.

IQRA Software All RIGHTS RESERVED 93


How Simulink Works

Simulink is a software package that enables you to model, simulate, and analyze the dynamic systems i.e.
the system whose outputs change over time. It can be used to explore the behavior of a wide range of real-
world dynamic systems, including electrical circuits, shock absorbers, braking systems, and many other
electrical, mechanical, and thermodynamic systems. This section explains how Simulink works. Simulating a
dynamic system is a two-step process with Simulink. First, a user creates a block diagram, using the
Simulink model editor that graphically depicts time-dependent mathematical relationships among the
system's inputs, states, and outputs. The user then commands Simulink to simulate the system represented
by the model from a specified start time to a specified stop time.
Simulink provides its own graphical editor that allows you to create and connect instances of block types,
selected from Simulink libraries. Simulink provides libraries of blocks representing elementary systems that
can be used to build a block. The blocks supplied with Simulink are called built-in blocks. Simulink users can
also create their own block types and can be added to Simulink library.
Simulink lets you to understand the following concept before start working on simulink.

Time: Time is an inherit component of block diagram in that the results of a block diagram simulation
change with time. A block diagram represents the instantaneous behavior of a dynamic system. Determining
a system's behavior over time thus entails repeatedly executing the model at intervals, called time steps,
from the start of the time span to the end of the time span. Simulink refers to the repeated execution of a
model at successive time steps as simulating the system that the model represents.

States: The output of some simulink model depends on the previous values or variables. Such variables are
called the states of system. Computing an outputs of a model from a block diagram hence entails saving the
value of states at the current time step for use in computing the outputs at a subsequent time step. Simulink
performs this task during simulation for models that define states. Two types of states can occur in a
Simulink model: discrete and continuous states. A continuous state changes continuously. A discrete state
is an approximation of a continuous state where the state is updated using finite (periodic or aperiodic)
intervals.
The following is a graphical representation of states of a block.

Block Parameters: The important properties of many standard blocks are parameterized. E.g, the Constant
value of the Simulink Constant block is a parameter. Simulink evaluates the expressions before running a

IQRA Software All RIGHTS RESERVED 94


simulation. You can change the values of parameters during a simulation. This allows you to determine
interactively the most suitable value for a parameter.
Many block parameters are tunable. A tunable parameter is a parameter whose value can change while
Simulink is executing a model. E.g, the gain parameter of the Gain block is tunable. You can alter the gain of
block, while a simulation is running. If a parameter is not tunable and the simulation is running, Simulink
disables the dialog box control that sets the parameter. Simulink allows you to specify that all parameters in
your model are nontunable except for those that you specify.

Block Sample Times: Every Simulink block is considered to have a sample time, even continuous blocks
and blocks that do not define states, such as the Gain block. Discrete blocks allow you to specify their
sample times via a Sample Time parameter. Continuous blocks are considered to have an infinitesimal
sample time called a continuous sample time. A block that is neither discrete nor continuous is said to have
an implicit sample time i.e. it inherits from its inputs (previous block).

Dynamic system simulation

Simulation of a dynamic system means the process of computing a system states and outputs over time
span. Simulink Engine responds to a Start command, performing the following steps.
Compilation: When you start the simulation, first of all Simulink engine invokes the model compiler. The
model compiler converts the model to an executable form, a process called compilation. In particular, the
compiler
• Evaluates the model's block parameter expressions to determine their values.
• Determines signal attributes, e.g., name, data type, numeric type, and dimensionality etc., checks
that each block can accept the signals connected to its inputs.
• Performs block reduction optimizations.
• Sorts the blocks into the order in which they need to be executed during the execution phase.
• Determines the sample times of all blocks in the model whose sample times you did not explicitly
specify.

Simulation Loop Phase: At the start of the simulation, the model specifies the initial states and outputs of
the system to be simulated. At each step, Simulink computes new values for the system's inputs, states, and
outputs and updates the model to reflect the computed values. At the end of the simulation, the model
reflects the final values of the system's inputs, states, and outputs. Simulink provides data display and
logging blocks. You can display and/or log intermediate results by including these blocks in your model.
At each time step, the Simulink Engine
• Computes the model's outputs.
• Computes the model's states.
• Optionally checks for discontinuities in the continuous states of blocks by zero crossing detection
method.
• Computes the time for the next time step.

IQRA Software All RIGHTS RESERVED 95


Zero-Crossing Detection: When simulating a dynamic system, Simulink checks for discontinuities in the
system's state variables at each time step, using a technique known as zero-crossing detection. Since the
value of the state variable might be undefined at discontinuous states. So, it is important to know the points
at which discontinuities appears.
A fixed-step solver computes the values of state variables at integral multiples of a fixed step size. However,
there is no guarantee that a point of discontinuity will occur at an integral multiple of the step size. Now if you
reduce the step size to increase the probability of finding a discontinuity, but this would greatly increase the
execution time.
A variable-step solver appears to offer a kind of solution. A variable-step solver adjusts the step size
dynamically, increasing the step size when a variable is changing slowly and decreasing the step size when
the variable changes rapidly. At discontinuity, a variable changes extremely rapidly. Thus, in theory, a
variable-step solver should be able to hit a discontinuity precisely. The problem is that to locate a
discontinuity accurately, a variable-step solver must again take many small steps, greatly slowing down the
simulation.
Now the point is that how Zero-Crossing Detection Works, a block can register a set of zero-crossing
variables with Simulink, each of which is a function of a state variable that can have a discontinuity. The
zero-crossing function passes through zero from a positive or negative value when the corresponding
discontinuity occurs. At the end of each simulation step, Simulink asks each block that has registered zero-
crossing variables to update the variables. Simulink then checks whether any variable has changed sign
since the last step. Such a change indicates that a discontinuity occurred in the current time step.
Zero-crossing signals have a direction attribute, which can have these values:
• Rising edge - A zero crossing occurs when a signal rises to or through zero, or when a signal
leaves zero and becomes positive.
• Falling edge - A zero crossing occurs when a signal falls to or through zero, or when a signal
leaves zero and becomes negative.
• Either - A zero crossing occurs if either a rising or falling condition occurs.

The following figure shows a signal that crosses zero. In the first curve, the integrator steps over the event
and the solver doesn’t detect the event. In the second curve, the solver detects the event.

Example to detect the zero crossing.

IQRA Software All RIGHTS RESERVED 96


Algebraic Loops: Some Simulink blocks have input ports with direct feedthrough. This means that the
output of these blocks cannot be computed without knowing the values of the signals entering the blocks at
these input ports. E.g. Math block, Integer block, Product block, Sum block etc.
When an input port is direct feedthrough by the output of the same block, either directly, or by a feedback
path through other blocks, an algebraic loop occurs. Example of algebraic loop,

Here the output y = 10 – y. i.e. y = 5.


But due to algebraic loop the output = 1.531e+017, which is a incorrect output.
Simulink models often contain algebraic loops. Simulink typically handles these by iterating to a solution for
every time step, adding delay to the model execution. Block Importer allows you to solve algebraic loops
symbolically and then export the resulting model back to Simulink, significantly improving the efficiency of
the model and its execution speed.

IQRA Software All RIGHTS RESERVED 97


Simulink Basics
Gathering Blocks

Each of the blocks you will use in this model will be taken from the Simulink Library Browser. To place the
Signal Generator block into the model window, follow these steps:
1) Click on the "+" in front of "Sources" (this is a subfolder beneath the "Simulink" folder) to display the
various source blocks available for us to use.
2) Scroll down until you see the "Signal Generator" block. Clicking on this will display a short
explanation of what that block does in the space below the folder list:

3) To insert a Sine Wave block into your model window, click on it in the Library Browser and drag the
block into your workspace.
Creating model

The same method can be used to place the Gain and Scope blocks in the model window. The "Gain" block
can be found in the "Math" subfolder and the "Scope" block is located in the "Sink" subfolder. Arrange the
three blocks in the workspace (done by selecting and dragging an individual block to a new location) so that
they look similar to the following:

IQRA Software All RIGHTS RESERVED 98


Modifying the Blocks Parameters

Simulink allows us to modify the blocks in our model so that they accurately reflect the characteristics of the
system we are analyzing. For example, we can modify the Signal Generator block by double-clicking on it.
Doing so will cause the following window to appear:

IQRA Software All RIGHTS RESERVED 99


This window allows us to select waveform, adjust the amplitude, frequency, and unit of the selected
waveform input. The "Sample time" value indicates the time interval between successive readings of the
signal.
Next, we modify the Gain block by double-clicking on it in the model window. The following window will then
appear:

Note that Simulink gives a brief explanation of the block's function in the top portion of this window. In case
of the Gain block, the signal input to the block (u) is multiplied by a constant (k) to create the block's output
signal (y). Changing the "Gain" parameter in this window changes the value of k.
For our system, we will let k = 5. Enter this value in the "Gain" field, and click "OK" to close the window.
The Scope block simply plots its input signal as a function of time, and thus there are no system parameters
that we can change for it. We will look at the Scope block in more detail after we have run our simulation.
Once model is ready save it. On saving, the simulink model takes extension .mdl. In this case the model
name block_diag.mdl

Running Simulations
Now model is built and ready to simulate. To start, go to the Simulation menu and click on Start, or just click
on the "Start/Pause Simulation" button in the model window toolbar. As our example is a simple model, the
simulation runs almost instantaneously. With more complicated systems, however, you will be able to see
the progress of the simulation by observing its running time in the the lower box of the model window.
Double-click the Scope block to view the output of the Gain block for the simulation as a function of time.
Once the Scope window appears, click the "Autoscale" button in its toolbar to scale the graph to better fit the
window. Having done this, you should see the following:

IQRA Software All RIGHTS RESERVED 100


Generating Document of Model

A Simulink model report is an HTML document that describes a model's structure and content. The report
includes block diagrams of the model and its subsystems and the settings of its block parameters
To generate a report of a model:
Step 1: Select File menu  Print details. The following Print Details dialog box appears.

Step 2: Select the desired report options on the dialog box.


Step 3: Select Print.
Simulink generates the HTML report in your system's default HTML browser.

IQRA Software All RIGHTS RESERVED 101


Simulink Solver

A solver is a component of the Simulink that determines the next simulation time step. It divides the time
span into a number of steps and solve the equation on each of these steps.
There are two types of solvers: fixed-step solver and variable-step solver
Both types of solvers compute the next simulation time as the sum of the current simulation time and a
quantity known as the step size.
Fixed-step solver: The fixed step solver divides the entire time span (start time to stop time) into fixed steps
using default step size 0.25 as follows

If start time is 0 and stop time is 10 s.


[0.0 0.25 0.5 0.75 1.0 1.25 ...10]

Variable-step solver: The variable step solver divides the entire time span (start time to stop time) into
variable steps using step size as follows
[0.0 0.5 0.75 1.0 1.5 2.0 2.25 ...10]
This significantly reduces the number of time steps required to simulate the model.
The variable-step discrete solver uses zero-crossing detection to handle continuous signals. By default,
Simulink use variable step solver.
The choice between the two types depends on how you plan to deploy your model. If you plan to generate
code from your model and run the code on a real-time target, choose a fixed-step solver to simulate the
model. A variable-step solver may cause the simulation to miss error conditions that can occur on a real-
time target.
A variable-step solver can shorten the time required to simulate your model significantly, while fixed step will
be time consuming.

Simulink Control Flow Blocks

Like in C language control flow statements, simulink also support control flow blocks, which are as follows

If-Else Control Flow block: The following shows a complete if-else control flow statement block

IQRA Software All RIGHTS RESERVED 102


The number of input and output can be adjusted by block Parameters dialog of the If block.

Switch Flow block: The following shows a complete switch control flow statement block.

While Flow block: The following shows a complete while control flow statement block.

For Flow block: The following shows a complete for control flow statement block.

IQRA Software All RIGHTS RESERVED 103


Subsystem & Masking

Subsystems

If you add more blocks to your model, model increases in size and complexity. There is one way to simplify
the model i.e. grouping number of blocks into one block. After grouping the one block is called as
subsystems.
It means number of blocks merging into one block.
The following are the advantages of creating subsystems.
• To reduce the number of blocks displayed in your model window.
• Allows you to keep functionally related blocks together.
• It enables you to establish a hierarchical block diagram, where a Subsystem block is on one layer
and the blocks that make up the subsystem are on another.

There are two ways, that you can create a subsystem.


• Add a Subsystem block to your model, then open that block and add more blocks it contains to the
subsystem window.
• Add the blocks that make up the subsystem, then group those blocks into a subsystem.

Creating a Subsystem

Following are the steps, by which you can create a subsystem.


Select the blocks and connecting lines that you want to include in the subsystem by enclosing them within
the box.

IQRA Software All RIGHTS RESERVED 104


Right click the selected blocks/lines and select the Create Subsystem or Choose Create Subsystem from
the Edit menu. Simulink replaces the selected blocks with a Subsystem block.

The name of Subsystem block is Subsystem and contains Inport and Outport to represent input from and
output to blocks outside the subsystem.
If you double click on subsystem, it displays the content of subsystem as follows.

The content of subsystem contains all the merging blocks and additionally Inport and Outport.

Labeling of Subsystem Ports

Simulink labels ports on a Subsystem block. The labels are the names of Inport and Outport of blocks.
The show or hide the port labels can be done by the following ways.

IQRA Software All RIGHTS RESERVED 105


• Select the Subsystem block, then right click and choose Hide Port Labels or Show Port Labels from
the Format menu.
• Selecting an Inport or Outport block in the subsystem and choosing Hide Name or Show Name
from the Format menu.
• Selecting the Show port labels option in the Subsystem block's parameter dialog.

Subsystem with label ports Subsystem with hide label ports

Conditionally Executed Subsystems

A conditionally executed subsystem is a subsystem whose execution depends on the value of an input
signal.
The input signal, which controls the execution of a subsystem, is called the control signal. Conditionally
executed subsystems are important in complex models, where one model is controlled by other model.
There are three types of conditionally executed subsystems as follows.

1. Enabled Subsystem: This subsystem executes when the input control signal is positive. The
execution of enabled subsystem starts, when control signal crosses zero (from the negative to the
positive direction) and continues execution while the control signal remains positive. If the control
input signal is a sine wave, the subsystem is alternately enabled and disabled.

Simulink uses the zero-crossing slope method to determine whether an enable is to occur. If the signal
crosses zero and the slope is positive, the subsystem is enabled.
How to create the enabled subsystem?
Double click the subsystem and open it. Copy an Enable block from the Signals & Systems library into a
subsystem. It creates the enabled subsystem.

2. Triggered subsystem: This subsystem executes once each time a trigger event occurs. A trigger
event can occur on the rising or falling edge of a trigger signal, which can be continuous or
discrete. The triggered subsystem can be executed by three ways.

IQRA Software All RIGHTS RESERVED 106


• Rising triggers execution of the subsystem.
• Falling triggers execution of the subsystem.
• Either triggers execution of the subsystem.

A triggered subsystem can be created by copying the Trigger block from the Signals & Systems library into a
subsystem. You can select the rising, falling, either by opening the block parameters.

3. Triggered and Enabled Subsystems: This subsystem executes when both triggered and enabled
condition becomes true. A triggered and enabled subsystem contains both an enable input port and
a trigger input port. This subsystem needs two control inputs to execute the subsystem.

A Triggered and Enabled subsystem can be created by copying the Trigger and enable block from the
Signals & Systems library into a subsystem.

IQRA Software All RIGHTS RESERVED 107


Masking Subsystems

Double click the subsystem; you can see the content of subsystem. If you want to hide the content of
subsystem, masking is required.
A mask is a custom user interface for a subsystem that hides the contents subsystem.
Mask Features: Masks can have any of the following features.
Mask Icon: The mask icon replaces a subsystem's standard icon, i.e., it appears in a block diagram in place
of the standard icon for a subsystem block.
• Mask Parameters: Simulink allows you to define a set of user-settable parameters for a masked
subsystem. Simulink stores the value of a parameter in the mask workspace as the value of a
variable whose name has been specified.
• Mask Parameter Dialog Box: The mask parameter dialog box replaces the subsystem's standard
parameter dialog box, i.e., on clicking the masked subsystem's icon, the mask dialog box appear
instead of the standard parameter dialog box for a Subsystem block.
• Mask Initialization Code: Simulink runs to initialize the masked subsystem at the start of a
simulation. You can use the initialization code to set the initial values of the masked subsystem's
mask parameters.

Creating Masked Subsystem: Now how to create the masked subsystem. The following example explains
the steps to create the masked subsystem.
Example
The simple subsystem models the equation for a line, y = mx + b.
Draw a simulink model to drive this equation as follows

IQRA Software All RIGHTS RESERVED 108


Create the subsystems for gain, summer and constant blocks

Right click on subsystems and select the Mask subsystem. The Mask editor window will be opened.

Mask editor contains four tabs


• Icon
• Parameters
• Initialization
• Documentation

IQRA Software All RIGHTS RESERVED 109


Fill up all the required values in all tabs and click ok.
Now if you double click on masked subsystem, it opens the following parameter box

Just enter the values of slope (m) and intercept (b). On supplying input values, you will be getting output
values.

IQRA Software All RIGHTS RESERVED 110


Simulink Debugger

Simulink Debugger
Simulink debugger allows you to run a simulation method by method, stopping the simulation after each
method, to examine the results. Here method means function that Simulink uses to solve a model at each
time step during the simulation.

Debugger's Graphical User Interface


Pull down the Tool menu from the model window and select Simulink Debugger. It displays the Simulink
debugger's graphical interface as shown below.

Start the simulation, all buttons in tool bar gets enabled as following.

IQRA Software All RIGHTS RESERVED 111


Select the Simulation Loop tab on the debugger window, you can see Simulation Loop pane. It contains
three columns as follows.

• Method: This column contains the methods (functions) that have been called during simulation with
expandable/collapsible nodes. Each node of the tree represents a method which calls other
methods. The block method names are hyperlinks. Click on a block method name, highlights the
corresponding block in the model diagram.
• Breakpoints: The breakpoints column consists of check boxes. Selecting a check box sets a
breakpoint at the method whose name appears to the left of the check box.
• ID Column: The ID column contains the IDs of the methods listed in the Methods column.

Outputs Pane
Outputs pane displays the same debugger output that appears in the MATLAB Command Window. The
output includes the debugger command prompt and the inputs, outputs, and a state of the block at whose
simulation is currently paused.

Sorted List Pane


If you select the Sorted List tab on the debugger window, the Sorted List tab will be displayed. The Sorted
List pane displays the sorted lists for the model being debugged.

Status Pane
If you select the Status Pane tab on the debugger window, the Status Pane tab will be displayed. The Status
pane displays the values of various debugger options and their status information.

Simulink Accelerator
The Simulink Accelerator is accelerates the simulation of Simulink models. It comes with the Simulink
Profiler that collects, analyzes, and displays simulation performance data. It minimizes the time needed to
simulate Simulink models.
The Simulink Accelerator speeds up the execution of Simulink model. The Accelerator uses portions of
Real-Time Workshop, which automatically generates C code from Simulink models, and C compiler to
create an executable.

How Accelerator Works: The Accelerator generates the C code from your Simulink model, and the
MATLAB mex function invokes the compiler and dynamically links the generated code to Simulink. Simulink
Accelerator removes much of the computational overhead required by Simulink models.
To run the model with Simulink Accelerator, pull down the Simulation menu and select Accelerator for the
model.

IQRA Software All RIGHTS RESERVED 112


To begin the simulation, select Start from the Simulation menu. When the simulation is started, the
Accelerator generates the C code and compiles it. It generates the following files and folders
• Generated code in a folder called modelname_accel_rtw. in this case, block_diag_accel_rtw.
• Places a compiled MEX-file (block_diag_acc.dll) in the current working directory.
• Runs the compiled model.

Profiler: The Simulink profiler collects performance data, while simulating the model and generating a
report, called a simulation profile.
The profiler measures the time required to execute each invocation of these functions and generates a
report at the end of the model that describes how much time has been spent in each function.

IQRA Software All RIGHTS RESERVED 113


Annotation

The textual information in the model is known as annotation. Annotations provide textual information about a
model.
To create a model annotation, double-click an unoccupied area of the block diagram. A small rectangle
appears and the cursor changes to an insertion point. Start typing the annotation contents. Each line is
centered within the rectangle that surrounds the annotation. To move an annotation, drag it to a new
location.

Overview of S-Functions

S-functions mean system-functions provide a powerful mechanism for extending the capabilities of Simulink.
You can find lot of existing blocks in the simulink library. At any point of time, if you don’t find any particular
block in the simulink library, you need to write S-functions to create the block. S-functions allow you to add
your own blocks to Simulink models.
An S-function is a computer language description of a Simulink block i.e. it transforms a computer language
program into a Simulink block.
S-functions can be written in
• MATLAB, called M-file S-function.
• C/C++, called C-mex S-function.
• Ada, or Fortran.

C, C++, Ada, and Fortran S-functions are compiled using mex utility
You can implement your mathematical algorithms in an S-function. After you write your S-function and place
its name in an S-Function block, you can customize the user interface by using masking.

IQRA Software All RIGHTS RESERVED 114


Simulink Applications

Example 1. Simulation of following equation


X(t) = A cos(wt + Ф)
where the displacement x is a function of time t, frequency w, phase angle phi, and amplitue A.
frequency w = 5, frequency=5 rad/sec, phase Ф =pi/2, amplitude A=2.

Here is the solution

Example 2: Solve the first order differential equation.

Note: The input is 1 after t> 0. This can be taken as a step function from the
Sources block library. Note however, that the stepping time is not t = 0 but t = 1.

IQRA Software All RIGHTS RESERVED 115


Here is the solution

In MATLAB Command window, you can see the result


[t,x,y]=sim('Equa2');
plot(t,x)
You can see the same graph.

Example 3: Solve the damped oscillator problem

Assume that u(t) = 0, i.e., there is no input.

Here is the solution

IQRA Software All RIGHTS RESERVED 116


The Fahrenheit to Celsius
Example 4: conversion of Fahrenheit to Celsius.
The formula is C = 5/9 (F - 32)
The simulink solve this equation as

You can solve it by using F2C block from simulink extra library.

IQRA Software All RIGHTS RESERVED 117


Matrix Multiplication
Example 5: Multiply the following matrices
A = [1 6 3]’; and B = [4 5 6];

Example 6: Create a model using a MinMax block to display the largest number in the row vector.
A = [1 -1 -4 5 7 -2 3 -5 6 9 -3 8 2 4 8 5]

Example 7: Create a model using the Reshape block to convert the row vector
to a 3 * 3 matrix.
A = [1 0 -3 -2 5 7 9 4 6]

IQRA Software All RIGHTS RESERVED 118


IQRA Software All RIGHTS RESERVED 119
LAB MANUAL

IQRA Software All RIGHTS RESERVED 120


Choose the correct one:

1. The Simulink model can be saved as an extension of


1. .djvu
2. .mat
3. .m
4. .mdl

2. Simulink can be launched without starting MATLAB


1. Yes
2. No
3. By using command prompt

3. To use MATLAB variables as a simulink block parameters, where do you need to define their
values?
1. Simulink library browser
2. MATLAB current directory
3. MATLAB workspace
4. Simulink model editor

4. Given a discrete multirate system using the fixed step solver, what would the fundamental
sample time be if the blocks in the model were sampled at 0.5 and 0.8?
1. 0.1
2. 0.3
3. 0.5
4. 1.2

5. What MATLAB command is used to run the simulink model from MATLAB command window.
1. sim
2. simulink
3. dspstart
4. commstartup

6. A number of blocks can be grouped into one block, this process is called as
1. Masking
2. Subsystem
3. Grouping blocks
4. None of above

IQRA Software All RIGHTS RESERVED 121


7. Let us consider the matrices A, B, C and defined at the MATLAB command prompt as:
A = [3+4j 1+0j 5−2j; 2−3j 4+j 7−4j; 1+6j 8−5j 4+7j];
B = [4+3j 0+2j -2+5j; -3+2j 6+7j -3-4j; 1+8j -5-3j 2-7j];
C = [-2+3j 7+2j -5-2j; 3-2j 4-7j -4+3j; -3+8j 7-4j -6+9j];
Create a model to compute the equation 2A + 3B - 5C.

8. Determines whether the determinants of the matrices defined below are equal or unequal.
A = [2 -3 5; 1 0 -1; -2 1 0];
B = [2 1 -2; -3 0 1; 5 -1 0];
Create a simulink model.

9. Create a model to display a sine wave with unity amplitude clipped at points +0.5 and -0.5.

10. Using Constant blocks, a Product block, and a Display block, perform the following operation.
(3 + j4) ⁄ (4 + j3) × (5 – j8)

11. Create a model using the Reshape block to convert the row vector
A = [1 0 -3 -2 5 7 9 4]
Into 4 * 2 matrix.

12. Create a model using an Abs block to display the magnitude of the expression

13. The vectors A and B are specified at the MATLAB command prompt as
A = [1 3 5 7 9]; B = [2 4 6 8];
The Width block outputs the sum of the widths of the vectors A and B.

14. Create a model to convert the Celsius to Fahrenheit.

15. Create a model to prove the following equations


3
(i) sin(3x) = 3 sin(x) - 4 sin (x)
4 2
(ii) cos(4x) = 8 cos (x) - 8 cos (x) + 1

IQRA Software All RIGHTS RESERVED 122

Das könnte Ihnen auch gefallen