Beruflich Dokumente
Kultur Dokumente
********
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
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.
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.
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.
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
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.
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 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
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,
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.
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
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 .
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 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.
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]
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.
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.
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.
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.
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
B = A – 15, returns
B= 1 -12 -13 -2
-10 -5 -4 -7
-6 -9 -8 -3
-11 0 -1 -14
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 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.
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.
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 + +, - +3.1416
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);
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;
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
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
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.
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.
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
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
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);
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.
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.
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
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.
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);
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
s = Hello
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';
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
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.
Reshaping a Matrix
The following functions change the shape of a matrix.
Function Description
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
A= 12 0 0 0
0 16 0 0
0 0 20 0
0 0 0 24
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.
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
Function Description
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];
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’);
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);
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
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.
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.
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.
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
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
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;
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
x = log(0);
isinf(x) returns
ans = 1
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.
x = 7i/0
x = NaN + Infi
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
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):
ans = 0
NaN ~= NaN
ans = 1
You can check the data type of a variable x using any of these commands.
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.
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
• 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.
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.
get(0, 'format')
Set the value for x and display in 5-digit scaled fixed point:
x = [4/3 1.2345e-6]
x = 1.3333 0.0000
format short e
x = 1.3333e+000 1.2345e-006
format long
x = 1.33333333333333 0.00000123450000
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
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.
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.
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.
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
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.
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)
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
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)
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
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.
Figure
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.
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).
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 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
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
15
b = 13
-9
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)
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.
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:
In MATLAB, make function file integrand2.m and save the following code
function z=integrand2(x,y)
z=sqrt(exp(x)).*sqrt(exp(y));
I2 =
1.6834
We will now take a look of the integrated area.
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;
The below figure shows the numerical solution of the equation using ode23.
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
Ans: _______________________________
Ans: _______________________________
Ans: _______________________________
Ans: _______________________________
Remarks: _____________________________
Ans: _______________________________
Ans: _______________________________
Ans: _______________________________
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.
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
Remarks: _____________________________
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
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
Ans: _______________________________
Ans: _______________________________
Ans: _______________________________
Ans: _______________________________
What are the values returned from the following function calls
Ans: _______________________________
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: _______________________________
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)
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.
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 .
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
6. Write a short code that will plot a sinusoid of frequency 50 Hz for 10 cycles.
Remarks: _____________________________
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
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.
12. Plot the real part and imaginary part of the following signal
x(t) = exp(0.5t + j(t+π/3))
Use interval [0, 10].
Remarks: _____________________________
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’.
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
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
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:
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:
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:
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.
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
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).
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.
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.
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:
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:
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:
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.
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
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.
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
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.
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.
Creating a Subsystem
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.
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.
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.
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.
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
Right click on subsystems and select the Mask subsystem. The Mask editor window will be opened.
Just enter the values of slope (m) and intercept (b). On supplying input values, you will be getting output
values.
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.
Start the simulation, all buttons in tool bar gets enabled as following.
• 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.
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.
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.
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.
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.
You can solve it by using F2C block from simulink extra library.
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]
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
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.