Nehru Arts and Science College
Department of Electronics and Communication Systems
E-Learning Material
Class: II MSC ECS
Paper: X
MATLAB PROGRAMMING
Unit – I Introduction
Mat lab environment – Help future – Types of files – Platform – Search path – Matlab
commands – Constants, Variables and Expressions: Character set – Data types – Constants and
Variables – Operators – Hierarchy of operators – Built-in functions – Assignment statement.
Unit – II Vectors and Matrices
Scalars and vectors – Entering data in matrices – Line continuation – matrix subscripts/indices –
Multidimensional matrices and arrays – Matrix manipulation – Generation of special matrices –
Matrix and array operations – Functions with array inputs – Structure arrays – Cell arrays.
Unit – III I/O Statements and Graphics
Data input – Interactive inputs – Reading/Storing file data – Output commands – Low level
input-output functions - Mat lab Graphics: Two dimensional plots – Multiple plots – Style
options – Sub plots – Specialized two dimensional plots – Three dimensional plots.
Unit – IV Control Structures and Mat lab Programming
Loops – Branches control structures – Matlab Programming: Matlab Editor – Matlab
Programming – Function Subprograms – Types of functions – Function handling – Errors and
warnings – Matlab debugger.
Unit – V Simulink
Introduction – Starting simulink – Simulink modelling – Solvers – Simulating a model – Using
variables from matlab – Data import/export – State space modelling and simulation – Simulation
of non-linear systems – obtaining state space model– Creating subsystems – Masked subsystems.
MATLAB Programming
Unit - I
Mat lab environment:
At startup, MATLAB automatically executes the master M-file matlabrc.m and, if it exists,
startup.m.matlabrc.m. The file matlabrc.m, which lives in the local directory, is reserved for use
by The MathWorks and, on multiuser systems, by your system manager.
startup.m. The file startup.m is for you to use. You can set default paths, define Handle
Graphics defaults, or predefine variables in your workspace.
Startup Options
You can specify startup options for MATLAB.
Add these options to the target path for your Windows shortcut for MATLAB. If you run
MATLAB from a DOS window, include these options with the startup command.
Startup
Option
Description
automation
Start MATLAB as an automation server, minimized, and without the MATLAB
splash screen. (For more information, see Chapter 7 of the Application Program
Interface Guide.)
logfile
logfilename
Automatically write output from MATLAB to the specified log file.
minimize
Start MATLAB minimized and without the MATLAB splash screen.
nosplash
Start MATLAB without displaying the MATLAB splash screen.
r M_file
Automatically run the specified M-file immediately after MATLAB starts.
regserver
Modify the Windows registry with the appropriate ActiveX entries for MATLAB.
(For more information, see Chapter 7 of the Application Program Interface
Guide.)
unregserver
Modify the Windows registry to remove the ActiveX entries for MATLAB. Use
this to reset the registry. (For more information, see Chapter 7 of the Application
Program Interface Guide.)
For a list of MATLAB startup options available for UNIX, at the UNIX prompt type
To quit MATLAB at any time, type quit at the MATLAB prompt.
On Windows platforms, you can also quit by selecting Exit from the File menu, or by using
the close box.
quit. quit runs the script finish.m, if finish.m exists anywhere on the MATLAB path.
finish.m. finish.m is a file you create that contains commands you want to run when MATLAB
terminates. Two sample finish.m files are in /toolbox/local:
finishsav.m - saves the workspace to a MAT-file when MATLAB quits
finishdlg.m - displays a dialog allowing you to cancel quitting
Matlab commands:
Command Line Editing
These are the main aspects of command line editing in MATLAB:
Basics of Command Line Editing (controlling input and output)
MATLAB Workspace
Search Path
Basics of Command Line Editing
These are the basic features of command line editing in MATLAB:
>> Prompt
Arrow and Control Keys
Clearing the Window
Paging of Output
Suppressing Output
Long Command Lines
Interrupting a Running Program
Controlling Numeric Format
>> Prompt. The prompt (>>) indicates MATLAB is ready to accept commands from you.
Arrow and Control Keys. Use these keys to help you edit in the command line.
Arrow Key Control Key Operation
Ctrl-p
Recall previous line.
Ctrl-n
Recall next line.
Ctrl-b
Move back one character.
Ctrl-f
Move forward one character.
ctrl-
Ctrl-r
Move right one word.
ctrl-
Ctrl-l
Move left one word.
home
Ctrl-a
Move to beginning of line.
end
Ctrl-e
Move to end of line.
esc
Ctrl-u
Clear line.
del
Ctrl-d
Delete character at cursor.
backspace
Ctrl-h
Delete character before cursor.
Ctrl-k
Delete (kill) to end of line.
Clearing the Window. Use clc to clear the Command Window.
This does not clear the workspace, but only clears the view. After using clc, you still can use the
up arrow key to see the history of the commands, one at a time.
Paging of Output. Use more to control paging of output in the Command Window.
By default, more is off. When you set more on, a page (screenful) of output displays at one time.
You then use:
Return
To advance to the next line
Space Bar To advance to the next page
q
To stop displaying the output
Suppressing Output. If you end a line with a semicolon, MATLAB performs the computation
but does not display any output.
Long Command Lines. If a statement does not fit on one line, use an ellipsis (three periods,
...), followed by Return or Enter to indicate that the statement continues on the next line.
For example,
s = 1 - 1/2 + 1/3 - 1/4 + 1/5 - 1/6 + 1/7 ...
- 1/8 + 1/9 - 1/10 + 1/11 - 1/12;
Interrupting a Running Program.
Press Ctrl-c at any time to interrupt a running program.
On Windows platforms, you may have to wait until an executing built-in function or MEXfile has finished its operation.
On UNIX systems, program execution terminates immediately.
Controlling Numeric Format. The format command controls the numeric format of the values
displayed on the screen.
The command affects only how numbers are displayed, not how MATLAB computes or saves
them. For more control over the output format, use sprintf and fprintf.
On Windows platforms, you can change the default format by selecting Preferences from
the File menu, and selecting the desired format from the General tab.
MATLAB Workspace
The MATLAB workspace contains a set of variables (named arrays) that you can manipulate
from the MATLAB command line.
These are the topics for using the MATLAB workspace:
Viewing the Workspace
Clearing the Workspace
Loading and Saving the Workspace
Viewing the Workspace.
workspace.
who gives the name
whos gives the name,
Use the who and whos commands to see what is currently in the
size, and data type information
Clearing the Workspace. Use clear to delete all existing variables from the workspace.
Loading and Saving the Workspace. MATLAB's save and load commands let you save the
contents of the MATLAB workspace at any time during a session and then reload the data back
into MATLAB during that session or a later one. load and save can also import and export text
data files.
On Windows platforms, the save operation is also available by selecting Save Workspace
As from the File menu. The load operation is also available by selecting Load
Workspace from the File menu.
Types of files – Platform – Search path:
Search Path
These topics are for working with files and directory structures:
About the Search Path
Search Path Rules
Viewing and Changing the Search Path
Default Search Path
Files on the Search Path
Current Directory
Opening Files in MATLAB
About the Search Path. MATLAB uses a search path to find M-files. MATLAB's M-files are
organized in directories or folders on your file system. Many of these directories of M-files are
provided along with MATLAB, while others are available separately as toolboxes.
Search Path Rules. If you enter the name foo at the MATLAB prompt, the MATLAB
interpreter:
1.
Looks for foo as a variable.
2.
Checks for foo as a built-in function.
3.
Looks in the current directory for a file named foo.m.
4.
Searches the directories on the search path for foo.m.
If you have more than one function with the same name, only the first one in the search path
order is found; other functions with the same name are considered to be shadowed and cannot be
executed.
Viewing and Changing the Search Path. Use these commands:
path, by itself, returns the current search path.
path(s), where s is a string, sets the path to s.
addpath /home/lib and path(path,'/home/lib') both append
directory to the path.
rmpath /home/lib removes the path /home/lib.
a new
Default Search Path. The default search path remembered between sessions is defined in the
file pathdef.m in the directory named local on your system. pathdef executes automatically each time
you start MATLAB.
On Windows platforms, you can directly edit pathdef.m with your text editor.
On UNIX workstations you may not have file system permission to edit pathdef.m. In this case,
put path and addpath commands in your startup.m file to change your path defaults.
MATLAB also provides a Path Browser with a convenient interface for viewing and changing
the search path. Use pathtool to start the Path Browser.
Files on the Search Path. Use these commands to see and use files on the search path.
Use path to display the search path.
Use what to see all of the MATLAB files in a directory. With no arguments, what displays
the files in the current directory.
Use type to see the code in a specific M-file.
Use edit to edit an M-file.
Current Directory.
MAT-files.
MATLAB maintains a current directory for working with M-files and
Use cd with no arguments to display the current directory.
Use cd with a path to change the current directory.
On Windows platforms, the initial current directory is specified in the shortcut file you use
to start MATLAB. Right-click on the shortcut file, and select Properties to change the default.
On UNIX systems, the initial current directory is the directory you are in on your UNIX file
system when you invoke MATLAB.
Opening Files in MATLAB. Use open to open files in MATLAB based on their extension as
shown in the table below.
Name
Action
Figure file (*.fig)
Open figure in a figure window
M-file (name.m)
Open M-file name in Editor
Model (name.mdl)
Open model name in Simulink
P-file (name.p)
Open the corresponding M-file, name.m, if it exists, in the Editor
Variable
Open array name in the Array Editor (the array must be numeric); open
calls openvar
Other extensions
(name.custom)
Open name.custom by calling the helper function opencustom, where
opencustom is a user-defined function.
Constants, Variables and Expressions:
MATLAB Variables, Keywords, and Constants
Variables are programmer-designated names that can represent a specific value of data. In
programming, these variables could either hold numeric, alphanumeric, or text type
data. Variables play an important role in computer programming as they enable programmers to
write flexible programs making it possible for the same program to process different sets of data.
Like other programming languages, MATLAB also has a set of rules for naming
variables. More specifically, the MATLAB variable-naming rules are as follows:
MATLAB Variables
Rules for Naming Variables
Variable names are case-sensitive.
Remarks and Examples
Name, name, NaMe, and NAME are all
different MATLAB variables.
Variable names can contain up to 31 characters. Any characters
thisismyvariablename
beyond the 31st will be ignored.
this_is_my_variable_name
Variable names must start with a letter, followed by any number of abc123
letters, digits, or underscores. Punctuation characters are not allowed Agent_007
since many of them have a special meaning in MATLAB.
x44
h_2_O
y
As presented above, it is already clear about how variables in MATLAB should be
named. However, there are exceptions to the naming rules. MATLAB has several names which
cannot be used as variables. These names are called keywords and they are a part of MATLAB's
reserved words list.
MATLAB Keywords
Shown below is a list of some of the keywords of MATLAB:
Reserved Words List
for end if while function return elseif case otherwise switch continue else
try catch global persistent break
If you try to use a reserved word as a variable, MATLAB will report an error. However, words
similar to those shown above can be used by capitalizing one or more letters. Example:
When reserved words are written in the MATLAB Command Window, they appear to be colored
blue. As shown above, when you try to assign values to the reserved words return and function,
they produce an error. But when you capitalize one or more letters, e.g. Return and fuNctioN,
they become valid expressions.
MATLAB Special Variables
In addition, MATLAB also has a number of special variables which stores constant values such
as:
MATLAB Constants
Special
Variables
Description
ans
Default variable name used for results.
beep
Make the computer produce a sound.
pi
Ratio of the circumference of a circle to its diameter.
eps
Smallest number such that, when added to 1, creates a number greater than 1 on the
computer.
inf
Stands for infinity. Example, 1/0.
NaN or nan
Stands for Not-a-Number. Example 0/0.
i or j
Stands for the square root of negative one (√−1 ).
nargin
Number of function input arguments.
nargout
Number of function output arguments.
realmin
Smallest usable positive real number.
realmax
Largest usable positive real number.
bitmax
Largest usable positive integer.
varargin
Variable number of function input arguments.
varargout
Variable number of function output arguments.
To use these special variables, just type them in the MATLAB Command Window:
>>
pi
ans
=
3.1416
>>
i
ans
=
0
+
1.0000i
>>
Furthermore, it is also possible to replace the values stored in each of the special variables:
>>
pi
ans
=
3.1416
>>
pi
=
pi
3
=
3
>>
pi
pi
=
3
>>
After assigning pi with a value of 3, everytime you type or use pi in the Command Window, the
result will always be 3. Now what if you wanted to revert the value of pi to its original value
which is 3.1416? You might ask if is there a way to do it? The answer is yes and its actually
very easy to do. Just use the command clear and the value of pi will change back to its default
value. See example below:
>>
>>
clear
pi
pi
ans
=
3.1416
>>
To explain further, when we assigned pi with the value of 3, the default value of pi is overwritten
and a new variable named pi having a value of 3 was stored in the MATLAB Workspace. That
is why whenever we use pi after the assignment, its value is always 3. By using the clear
command the variable name pi was deleted in the MATLAB Workspace, hence, the value of pi
was
reverted
back
to
its
default
value
3.1416.
However, just like any special variables, the clear command could also be assigned with another
value. And by doing so, you can no longer use clear to delete variables in the MATLAB
Workspace. To illustrate more about this situation, take a look at the example below:
In the example above, we assigned pi with a value of 3 and we assigned clear with a value of
2. Now, we wanted to change back pi to its default value 3.1416 but when we had written clear
pi, MATLAB produced an error. Why? That is because the original function of clear was
overwritten when we assigned it with the value of 2. So how do we reset the values of these
special variables now that we can no longer use clear? Easy, just go to the MATLAB
Workspace and select the name of the variable you want to delete. You can right-click the
variable name and select delete or you can also press the delete icon. After that, you will be
prompted with a message box for your confirmation. Just press ok and everything will return to
normal. You can now again reuse the clear command with its original function.
Hierarchy of operators :
An Introduction to MATLAB: Basic Operations
Contents
Arithmetic Operations and Functions
Variables In MATLAB
Arrays
Plotting
Arithmetic Operations on Arrays
Exercises
Exercise 1
Exercise 2
Exercise 3
Exercise 4
MATLAB is a programming language that is very useful for numerical simulation and data
analysis. The following tutorials are intended to give you an introduction to scientific computing
in MATLAB.
Lots of MATLAB demos are available online at
http://www.mathworks.com/academia/student_center/tutorials/launchpad.html
You can work through these at your leisure, if you want. Everything you need for EOS 225
should be included in the following tutorials.
Arithmetic Operations and Functions
At its simplest, we can use MATLAB as a calculator. Type
3+2
What do you get?
3+2
ans =
5
Built-in functions:
MATLAB has several built in functions that can do specific mathematical operations. You can use it to great
advantage by using them instead of writing your own.
For example sin, cos, ode45, ezplot, log, contour, etc
The actual functions you can use depends on the MATLAB toolboxes that are installed on the computer where you
will be running the piece of MATLAB code.
It is recommended that you use variable names that are not the same as the built in function names
To know what functions are available is essential before you can use it (they can be used only in specified manner)
or avoid defining variables with the same name. The help command is the best resource to accomplish this
>> help elfun
% will display the elementary functions you can use
>> help specfun % will display special functions - bessel, gamma etc
Matlab Functions:
One of the most powerful ways to use MATLAB is through breaking up the code into smaller execution
units that does only a specific task. These are called functions. They are also refferred to subroutines in
other languages. In VB these correspond to Function and Sub procedures.
In Matlab there are built-in functions and the ones you create.
Matlab built-in functions
There are three types of built-in functions types available in MATLAB
Elementary built-in functions
Typing
help elfun at the prompt will give you a list of these functions
Elementary math functions.
Trigonometric.
sin
- Sine.
sinh
- Hyperbolic sine.
asin
- Inverse sine.
asinh
- Inverse hyperbolic sine.
cos
- Cosine.
cosh
- Hyperbolic cosine.
acos
- Inverse cosine.
acosh
- Inverse hyperbolic cosine.
tan
- Tangent.
tanh
- Hyperbolic tangent.
atan
- Inverse tangent.
atan2
- Four quadrant inverse tangent.
atanh
- Inverse hyperbolic tangent.
sec
- Secant.
sech
- Hyperbolic secant.
asec
- Inverse secant.
asech
- Inverse hyperbolic secant.
csc
- Cosecant.
csch
- Hyperbolic cosecant.
acsc
- Inverse cosecant.
acsch
- Inverse hyperbolic cosecant.
cot
- Cotangent.
coth
- Hyperbolic cotangent.
acot
- Inverse cotangent.
acoth
- Inverse hyperbolic cotangent.
Exponential.
exp
- Exponential.
log
- Natural logarithm.
log10
- Common (base 10) logarithm.
log2
- Base 2 logarithm and dissect floating point number.
pow2
- Base 2 power and scale floating point number.
sqrt
- Square root.
nextpow2 - Next higher power of 2.
Complex.
abs
- Absolute value.
angle
- Phase angle.
conj
- Complex conjugate.
imag
- Complex imaginary part.
real
- Complex real part.
unwrap - Unwrap phase angle.
isreal
- True for real array.
cplxpair - Sort numbers into complex conjugate pairs.
Rounding and remainder.
fix
- Round towards zero.
floor
- Round towards minus infinity.
ceil
- Round towards plus infinity.
round
- Round towards nearest integer.
mod
- Modulus (signed remainder after division).
rem
- Remainder after division.
sign
- Signum.
Assignment statement:
MATLAB
Basics II: Assignment statements and conditional statements
1
Start a MATLAB
session by clicking on the MATLAB. In this handout, we will work only in the
Command Window.Anassignment statement assigns a number to a variable. The pseudocode
we use in this course for assignment statements is, for example,
x←
22, which assigns the number
22
to the variable x
.TheMATLAB code for this statement is simply
>> x = 22;
Try checking the content of the variable x:
>> x
Now MATLAB tells you that the value of the variable
X is 22
, which makes sense, since this is the
value we assigned to this variable. The semicolon at the end of the assingment statement (or
any other statement) has the effect of suppressing output. Note that M
ATLAB did not give you any answer after you entered the assignment statement, it just gave
you the next prompt. See what happens if you leave
out the semicolon:
>> x = -pi
The order of symbols is of paramount importance in assignment statements. Try entering
now:
>> x = y;
This will give you an error message, since we are trying to assign the value of a variable
Y to the variable x
, but so far, we did not assign any value to a variable
y. In contrast, if you enter
>>z=x
you will find that the value
π that had been previously assigned to x is now also assigned to the variable
z. This did in no way alter the content of x, as you can convince yourself by entering
>> x It is quite easy though to alter the contents of a variable with an assignment statement.
For example, in order to increase the value of xby1we can enter:
>>x=x+1
Of course, the above expression seems to be just a mathematical absurdity, but you need to
keep in
mind that the “
=
” sign stands for an assignment statement, not for equality of two numbers. The
precise meaning of this command is: “Take the current value of the variable
x
, increase it by one, and
assign the result to the variable
x
.”
Again, order of symbols is of paramount importance; you will get an error message if you if
you enter:
>>x+1=x
Now let us try to assign the absolute value of the variable
X to a new variable
may have more than one letter. We will pretend that we do not know the current
value of x , and we will also not use at this time MATLAB’s built-in command
abs(x)
for finding the
absolute value. Since the absolute value of a number depends on whether this number is
nonnegative 2005 Winfried Just, Department of Mathematics, Ohio University. All rights reserved.
or negative, we will need to use a conditional statement.This can be done at the command
line as
follows:
>> if x >= 0; absx = x; else absx = -x; end
You can check the contents of the variable
absx
by entering:
>> absx
A conditional statement in MATLAB has the following structure:
if
(a certain condition holds) (exe-cute one set of statements)
else
(execute another set of statements)
end
The
Else is optional, but the end is obligatory. It is interesting to note that MATLAB ’s symbol for
≥ is >=
.
Unit-II
Vectors and Matrices
Scalars and vectors:
Overview
Although matrices are two dimensional, they do not always appear to have a rectangular shape.
A 1-by-8 matrix, for example, has two dimensions yet is linear. These matrices are described in
the following sections:
The Empty Matrix
An empty matrix has one or more dimensions that are equal to zero. A two-dimensional
matrix with both dimensions equal to zero appears in the MATLAB® application as [].
The expression A = [] assigns a 0-by-0 empty matrix to A.
Scalars
A scalar is 1-by-1 and appears in MATLAB as a single real or complex number (e.g., 7,
583.62, -3.51, 5.46097e-14, 83+4i).
Vectors
A vector is 1-by-n or n-by-1, and appears in MATLAB as a row or column of real or
complex numbers:
Column Vector
53.2
87.39
4-12i
43.9
Row Vector
53.2 87.39 4-12i 43.9
The Empty Matrix
A matrix having at least one dimension equal to zero is called an empty matrix. The simplest
empty matrix is 0-by-0 in size. Examples of more complex matrices are those of dimension 0-by5 or 10-by-0.
To create a 0-by-0 matrix, use the square bracket operators with no value specified:
A = [];
whos A
Name
A
Size
0x0
Bytes Class
0 double array
You can create empty matrices (and arrays) of other sizes using the zeros, ones, rand, or eye
functions. To create a 0-by-5 matrix, for example, use
A = zeros(0,5)
Operating on an Empty Matrix
The basic model for empty matrices is that any operation that is defined for m-by-n matrices, and
that produces a result whose dimension is some function of m and n, should still be allowed when
m or n is zero. The size of the result of this operation is consistent with the size of the result
generated when working with nonempty values, but instead is evaluated at zero.
For example, horizontal concatenation
C = [A B]
requires that A and B have the same number of rows. So if A is m-by-n and B is m-by-p, then C is
m-by-(n+p). This is still true if m or n or p is zero.
As with all matrices in MATLAB, you must follow the rules concerning compatible dimensions.
In the following example, an attempt to add a 1-by-3 matrix to a 0-by-3 empty matrix results in
an error:
[1 2 3] + ones(0,3)
Error using +
Matrix dimensions must agree.
matrix subscripts/indices:
Syntax
[I,J] = ind2sub(siz,IND)
[I1,I2,I3,...,In] = ind2sub(siz,IND)
Description
The ind2sub command determines the equivalent subscript values corresponding to a single index
into an array.
returns the matrices I and J containing the equivalent row and column
subscripts corresponding to each linear index in the matrix IND for a matrix of size siz. siz is a
vector with ndim(A) elements (in this case, 2), where siz(1) is the number of rows and siz(2) is the
number of columns.
[I,J] = ind2sub(siz,IND)
Note For matrices, [I,J] = ind2sub(size(A),find(A>5)) returns the same values as [I,J] =
find(A>5).
returns n subscript arrays I1,I2,...,In containing the equivalent
multidimensional array subscripts equivalent to IND for an array of size siz. siz is an n-element
vector that specifies the size of each array dimension.
[I1,I2,I3,...,In] = ind2sub(siz,IND)
Examples
Example 1 — Two-Dimensional Matrices
The mapping from linear indexes to subscript equivalents for a 3-by-3 matrix is
This code determines the row and column subscripts in a 3-by-3 matrix, of elements with linear
indices 3, 4, 5, 6.
IND = [3 4 5 6]
s = [3,3];
[I,J] = ind2sub(s,IND)
I=
3
1
2
3
1
2
2
2
J=
Multidimensional matrices and arrays:
Overview
An array having more than two dimensions is called a multidimensional array in the MATLAB®
application. Multidimensional arrays in MATLAB are an extension of the normal twodimensional matrix. Matrices have two dimensions: the row dimension and the column
dimension.
You can access a two-dimensional matrix element with two subscripts: the first representing the
row index, and the second representing the column index.
Multidimensional arrays use additional subscripts for indexing. A three-dimensional array, for
example, uses three subscripts:
The first references array dimension 1, the row.
The second references dimension 2, the column.
The third references dimension 3. This illustration uses the concept of a page to represent
dimensions 3 and higher.
To access the element in the second row, third column of page 2, for example, you use the
subscripts (2,3,2).
As you add dimensions to an array, you also add subscripts. A four-dimensional array, for
example, has four subscripts. The first two reference a row-column pair; the second two access
the third and fourth dimensions of data.
Most of the operations that you can perform on matrices (i.e., two-dimensional arrays) can also
be done on multidimensional arrays.
Note The general multidimensional array functions reside in the datatypes directory.
Creating Multidimensional Arrays
You can use the same techniques to create multidimensional arrays that you use for twodimensional matrices. In addition, MATLAB provides a special concatenation function that is
useful for building multidimensional arrays.
This section discusses
Generating Arrays Using Indexing
Extending Multidimensional Arrays
Generating Arrays Using MATLAB Functions
Building Multidimensional Arrays with the cat Function
Generating Arrays Using Indexing
One way to create a multidimensional array is to create a two-dimensional array and extend it.
For example, begin with a simple two-dimensional array A.
A = [5 7 8; 0 1 9; 4 3 6];
A is
a 3-by-3 array, that is, its row dimension is 3 and its column dimension is 3. To add a third
dimension to A,
A(:,:,2) = [1 0 4; 3 5 6; 9 8 7]
MATLAB responds with
A(:,:,1) =
5 7
0 1
4 3
8
9
6
A(:,:,2) =
1 0
3 5
9 8
4
6
7
You can continue to add rows, columns, or pages to the array using similar assignment
statements.
Matrix and array operations:
Arithmetic Operators + - * / \ ^ '
Matrix and array arithmetic
Syntax
A+B
A-B
A*B
A.*B
A/B
A./B
A\B
A.\B
A^B
A.^B
A'
A.'
Description
MATLAB® software has two different types of arithmetic operations. Matrix arithmetic
operations are defined by the rules of linear algebra. Array arithmetic operations are carried out
element by element, and can be used with multidimensional arrays. The period character (.)
distinguishes the array operations from the matrix operations. However, since the matrix and
array operations are the same for addition and subtraction, the character pairs .+ and .- are not
used.
+
Addition or unary plus. A+B adds A and B. A and B must have the same size, unless one is a
scalar. A scalar can be added to a matrix of any size.
-
Subtraction or unary minus. A-B subtracts B from A. A and B must have the same size, unless
one is a scalar. A scalar can be subtracted from a matrix of any size.
*
Matrix multiplication. C = A*B is the linear algebraic product of the matrices A and B. More
precisely,
For nonscalar A and B, the number of columns of A must equal the number of rows of B. A
scalar can multiply a matrix of any size.
.*
Array multiplication. A.*B is the element-by-element product of the arrays A and B. A and B
must have the same size, unless one of them is a scalar.
/
Slash or matrix right division. B/A is roughly the same as B*inv(A). More precisely, B/A =
(A'\B')'. See the reference page for mrdivide for more information.
./
Array right division. A./B is the matrix with elements A(i,j)/B(i,j). A and B must have the same
size, unless one of them is a scalar.
\
Backslash or matrix left division. If A is a square matrix, A\B is roughly the same as inv(A)*B,
except it is computed in a different way. If A is an n-by-n matrix and B is a column vector with
n components, or a matrix with several such columns, then X = A\B is the solution to the
equation AX = B. A warning message is displayed if A is badly scaled or nearly singular. See
the reference page for mldivide for more information.
If A is an m-by-n matrix with m ~= n and B is a column vector with m components, or a matrix
with several such columns, then X = A\B is the solution in the least squares sense to the underor overdetermined system of equations AX = B. The effective rank, k, of A is determined from
the QR decomposition with pivoting. A solution X is computed that has at most k nonzero
components per column. If k < n, this is usually not the same solution as pinv(A)*B, which is the
least squares solution with the smallest norm
.
.\
Array left division. A.\B is the matrix with elements B(i,j)/A(i,j). A and B must have the same
size, unless one of them is a scalar.
^
Matrix power. X^p is X to the power p, if p is a scalar. If p is an integer, the power is computed
by repeated squaring. If the integer is negative, X is inverted first. For other values of p, the
calculation involves eigenvalues and eigenvectors, such that if [V,D] = eig(X), then
X^p = V*D.^p/V.
If x is a scalar and P is a matrix, x^P is x raised to the matrix power P using eigenvalues and
eigenvectors. X^P, where X and P are both matrices, is an error.
.^
Array power. A.^B is the matrix with elements A(i,j) to the B(i,j) power. A and B must have the
same size, unless one of them is a scalar.
'
Matrix transpose. A' is the linear algebraic transpose of A. For complex matrices, this is the
complex conjugate transpose.
.'
Array transpose. A.' is the array transpose of A. For complex matrices, this does not involve
conjugation.
Structure arrays – Cell arrays:
struct2cell
Convert structure to cell array
Syntax
c = struct2cell(s)
Description
c = struct2cell(s)
converts the m-by-n structure s (with p fields) into a p-by-m-by-n cell array c.
If structure s is multidimensional, cell array c has size [p size(s)].
Examples
The commands
clear s, s.category = 'tree';
s.height = 37.4; s.name = 'birch';
create the structure
s=
category: 'tree'
height: 37.4000
name: 'birch'
Converting the structure to a cell array,
c = struct2cell(s)
c=
'tree'
[37.4000]
'birch'
Unit – III
I/O Statements and Graphics Data input
Syntax
A = fscanf(fileID, format)
A = fscanf(fileID, format, sizeA)
[A, count] = fscanf(...)
Description
A = fscanf(fileID, format) reads and converts data from a text file into array A in column order.
To convert, fscanf uses the format and the encoding scheme associated with the file. To set the
encoding scheme, use fopen. The fscanf function reapplies the format throughout the entire file,
and positions the file pointer at the end-of-file marker. If fscanf cannot match the format to the
data, it reads only the portion that matches into A and stops processing.
A = fscanf(fileID, format, sizeA) reads sizeA elements into A, and positions the file pointer after
the last element read. sizeA can be an integer, or can have the form [m,n].
[A, count] = fscanf(...) returns the number of elements that fscanf successfully reads.
Input Arguments
fileID
Integer file identifier obtained from fopen.
format
String enclosed in single quotation marks that describes each type of
element (field). Includes one or more of the following specifiers.
Field Type
Specifier
Details
Integer,
signed
%d
Base 10
%i
Base determined from the values. Defaults
to base 10. If initial digits are 0x or 0X, it is
base 16. If initial digit is 0, it is base 8.
%ld or %li 64-bit values, base 10, 8, or 16
Integer,
unsigned
%u
Base 10
%o
Base 8 (octal)
%x
Base 16 (hexadecimal)
%lu, %lo, 64-bit values, base 10, 8, or 16
%lx
Floatingpoint
number
%f
%e
Floating-point fields can contain any of the
following (not case sensitive): Inf, -Inf,
NaN, or -NaN.
%g
Character
string
%s
Read series of characters, until find white
space.
%c
Read any single character, including white
space.
(To read multiple characters, specify field
length.)
%[...]
Read only characters in the brackets, until
the first nonmatching character or white
space.
Optionally:
To skip fields, insert an asterisk (*) after the percent sign (%). For
example, to skip integers, specify %*d.
To specify the maximum width of a field, insert a number. For example,
%10c reads exactly 10 characters at a time, including white space.
To skip a specific set of characters, insert the literal characters in the
format. For example, to read only the floating-point number from
'pi=3.14159', specify a format of 'pi=%f'.
Dimensions of the output array A. Specify in one of the following forms:
inf
Read to the end of the file. (default)
n
Read at most n elements.
[m,n] Read at most m*n elements in column order. n can be inf, but m
cannot.
When the format includes %s, A can contain more than n columns. n
refers to elements, not characters.
Output Arguments
An array. If the format includes:
Only numeric specifiers, A is numeric. If format includes only 64-bit
signed integer specifiers, A is of class int64. Similarly, if format includes
only 64-bit unsigned integer specifiers, A is of class uint64. Otherwise, A is
of class double. If sizeA is inf or n, then A is a column vector. If the input
contains fewer than sizeA elements, MATLAB® pads A with zeros.
Only character or string specifiers (%c or %s), A is a character array. If
sizeA is inf or n, A is a row vector. If the input contains fewer than sizeA
characters, MATLAB pads A with char(0).
A combination of numeric and character specifiers, A is numeric, of class
double. MATLAB converts each character to its numeric equivalent. This
conversion occurs even when the format explicitly skips all numeric values
(for example, a format of '%*d %s').
If MATLAB cannot match the input to the format, and the format contains
both numeric and character specifiers, A can be numeric or character. The
class of A depends on the values MATLAB reads before processing stops.
count
The number of elements fscanf reads into A.
Examples
Read the contents of a file. fscanf reuses the format throughout the file, so you do not need a
control loop:
% Create a file with an exponential table
x = 0:.1:1;
y = [x; exp(x)];
fid = fopen('exp.txt', 'w');
fprintf(fid, '%6.2f %12.8f\n', y);
fclose(fid);
% Read the data, filling A in column order
% First line of the file:
% 0.00
1.00000000
fid = fopen('exp.txt');
A = fscanf(fid, '%g %g', [2 inf]);
fclose(fid);
% Transpose so that A matches
% the orientation of the file
A = A';
Skip specific characters in a file, and return only numeric values:
% Create a file with temperatures
tempstr = '78°F 72°F 64°F 66°F 49°F';
fid = fopen('temperature.dat', 'w+');
fprintf(fid, '%s', tempstr);
% Return to the beginning of the file
frewind(fid);
% Read the numbers in the file, skipping the units
% num_temps is a numeric column vector
degrees = char(176);
num_temps = fscanf(fid, ['%d' degrees 'F']);
fclose(fid);
INTRACTIVE INPUTS
extinput
Interactive input of text
Syntax
textinput(<prompt1>)
textinput(<prompt1>, x1, <prompt2>, x2, …)
Description
textinput
allows interactive input of text.
textinput()
displays the prompt "Please enter text:" and waits for input by the user. The
input is converted to a character string, which is returned as the function's return value.
textinput(prompt1)
enter text:".
uses the character string prompt1 instead of the default prompt "Please
textinput( prompt1 x1) converts the input to a character string and assigns this string to
identifier or local variable x1. The default prompt is used, if no prompt string is specified.
the
Several input values can be read with a single textinput command. Each identifier in the
sequence of arguments makes textinput return a prompt, waiting for input to be assigned to the
identifier or variable. A character string preceeding the identifier or variable in the argument
sequence replaces the default prompt. Cf. Example 3. Arguments that are neither prompt strings
nor identifiers or variables are ignored.
The input may extend over several lines. In the output string, MuPAD® uses the character \n
(carriage return) to separate lines.
Input characters with a leading \ are not interpreted as control characters, but as two separate
characters.
The identifiers or variables x1 etc. may have values. These are overwritten by textinput.
Examples
Example 1
The default prompt is displayed, the input is converted to a character string and returned:
textinput()
Please enter text input: << myinput >>
Example 2
A user-defined prompt is used, the input is assigned to the identifier x:
textinput("enter your name: ", x)
enter your name: << Turing >>
x
delete x:
Example 3
If several values are to be read, separate prompts can be defined for each value:
textinput("She: ", hername, "He:
She: << Bonnie >> He: <<
Clyde >>
", hisname)
hername, hisname
delete hername, hisname:
Parameters
prompt1, prompt2,
…
Input prompts: character strings
x1, x2, …
identifiers or local variables
Reading/stroring file data
File input/output Saving/reading binary files and making calls to the operating system
When using MATLAB, either when running a m file or performing calculations interactively,
there is a master memory structure that MATLAB uses to keep track of the values of all of the
variables. This memory space can be written in a binary format to a file for storing the results of
your calculations for later use. This is often useful when you have to interrupt a MATLAB
session. The following commands demonstrate how to use this storage option to make binary
.mat files. First, let us define some variables that we want to save.
num_pts =10;
Afull=zeros(num_pts,num_
pts);
Afull(1,1) = 1;
Afull(num_pts,num_pts) = 1;
for i=2:(num_pts
1) sum over interior points
Afull(i,i) = 2;
Afull(i,i
1) =
1;
Afull(i,i+1) =
1;
end
b = linspace(0,1,num_pts)';
x = Afull
\
b;
whos; display contents of memory
The "save" command saves the data in the memory space to the named binary file.
save mem_store1.mat;
clear all;
whos;
no variables are stored in memory
ls *.mat
display all .mat files in directory
The "load" command loads the data stored in the named binary file into m
emory.
load mem_store1.mat;
whos;
we see that the data has been loaded again
If we want to get rid of this file, we can use the "delete" command.
delete mem_store1.mat;
ls *.mat
In the commands above, I have used path names to specify the directory.
We can view our
current default directory using the command "pwd".
pwd
displays the current directory
We can then change to another directory using the "cd" command.
cd ..
move up one directory
pwd
ls
list files in directory
cd MATLAB_tutorial;
direc
tory name may differ for you
pwd; ls
We can also use the "save" command to save only selected variables to a binary file.
save mem_store2.mat Afull;
clear all
whos
load mem_store2.mat
whos
delete mem_store2.mat
clear all
Input/output of data
to/from an ASCII file
First, let use define some variables that we want to save.
num_pts =10;
Afull=zeros(num_pts,num_pts);
Afull(1,1) = 1;
Afull(num_pts,num_pts) = 1;
for i=2:(num_pts
1) sum over interior points
Afull(i,i) = 2;
Afull(i,i
1) =
1;
Afull(i,i+1) =
1;
end
b = linspace(0,1,num_pts)';
x = Afull
\
b;
whos; display contents of memory
Now, let us write out the contents of Afull into a file that we can read.
One option is to use the "save" command with the option
ascii;
type store1.dat
view contents of file
We can also load a file in this manner. The contents of the ASCII file filename.dat are stored in
the MATLAB variable filename. This is a good way to i
mport data from experiments or other
programs into MATLAB.
load store1.dat;
If we add the option
double, the data is printed out with double the amount of digits for
higher precision.
delete store1.dat;
save store1.dat Afull
ascii
double;
type stor
e1.dat
We can use this command with multiple variables, but we see that no spaces are added.
delete store1.dat;
save store1.dat Afull b x
ascii;
type store1.dat
view contents of file
delete store1.dat
get rid of file
MATLAB also allows more complex
formatted file input/output of data using commands that
are similar to those in C.
First, we list all of the files in the directory.
ls
Next, we see create the output file and assign a label to it
with the "fopen" command that has the syntax
FID = fop
en(FILENAME,PERMISSION)
where PERMISSION is usually one of :
'r' = read only
'w' = write (create if needed)
'a' = append (create if needed)
'r+' = read and write (do not create)
'w+' = create for read and write
'a+' = read and append (create if need
ed)
FID_out = fopen('test_io.dat','w');
ls
Now, we print the b vector to the output file as a column vector using the "fprintf" command.
In the FORMAT string '
\
n' signifies a carriage return, and 10.5f specifies a floating point
decimal output with 5 nu
mbers after the decimal point and a total field width of 10.
for i=1:length(b)
fprintf(FID_out,'10.5f
\
n',b(i));
end
We now close the file and show the results.
fclose(FID_out);
disp('Contents of test_io.dat : ');
type test_io.dat;
MATLAB's "fprint
f" can also be loaded to avoid the need of
using a for loop
FID_out = fopen('test_io.dat','a');
fprintf(FID_out,'
\
n');
fprintf(FID_out,'10.5f
\
n',x);
fclose(FID_out);
disp('Contents of test_io.dat : ');
type test_io.dat;
We can also use "fprintf" t
o print out a matrix.
C = [1 2 3; 4 5 6; 7 8 9; 10 11 12];
FID_out = fopen('test_io.dat','a');
fprintf(FID_out,'
\
n');
for i = 1:size(C,1)
fprintf(FID_out,'5.0f 5.0f 5.0f
\
n',C(i,:));
end
fclose(FID_out);
disp('Contents of test_io.dat : ');
type te
st_io.dat;
We can read in the data from the formatted file using
"fscanf", which works similarly to "fprintf".
Output commands
Format Line Spacing in Output
By default, MATLAB® displays blanks lines in command output.
You can select one of two numeric display options in MATLAB.
loose—Keeps the display of blank lines (default)
>> x = [4/3 1.2345e-6]
x=
1.3333
0.0000
compact—Suppresses the display of blank lines
>> x = [4/3 1.2345e-6]
x=
1.3333 0.0000
To format the output display, do one of the following:
On the Home tab, in the Environment section, select Preferences > Command Window, and
then choose a Numeric format option.
Use the format function at the command line, for example:
format loose
format compact
Format Floating-Point Numbers
You can change the way numbers display. By default, MATLAB uses the short format (5-digit
scaled, fixed-point values).
For example, suppose you enter x = [4/3 1.2345e-6] in the Command Window. The
MATLAB output display depends on the format you selected.
Output Display Format Example Output
short (default)
x = 1.3333 0.0000
short e
x = 1.3333e+00 1.2345e-06
+
x = ++
Note: The text display format affects only how numbers are shown, not how MATLAB
computes or saves them.
Wrap Lines of Code to Fit Window Width
A line of code or its output can exceed the width of the Command Window, requiring you to use
the horizontal scroll bar to view the entire line. To break a single line of input or output into
multiple lines to fit within the current width of the Command Window:
On the Home tab, in the Environment section, select Preferences > Command Window.
Select Wrap Lines.
Click OK.
Suppress Output
To suppress code output, add a semicolon (;) to the end of a command. This is particularly useful
when code generates large matrices.
Running the following code creates A, but does not show the resulting matrix in the Command
Window:
A = magic(100);
View Output by Page
Output in the Command Window might exceed the visible portion of the window. You can view
the output, one screen at a time:
In the Command Window, type more on to enable paged output.
Type the command that generates large output.
View the output:
Advance to the next line by pressing Enter.
Advance to the next page by pressing Space Bar.
Stop displaying the output by pressing q.
To disable paged output, type more off.
Clear the Command Window
If the Command Window seems cluttered, you can clear all the text (without clearing the
workspace) by doing one of the following:
On the Home tab, in the Code section, select Clear Commands > Command Window to clear
the Command Window scroll buffer.
Use the clc function to clear the Command Window scroll buffer.
Use the home function to clear your current view of the Command Window, without clearing
the scroll buffer.
Low level input /Output functions
Low-Level File I/O
Read and write operations at the byte or character level
MATLAB Functions
fclose Close one or all open files
feof
Test for end-of-file
ferror Information about file I/O errors
fgetl
Read line from file, removing newline characters
fgets
Read line from file, keeping newline characters
fopen Open file, or obtain information about open files
fprintf Write data to text file
fread
Read data from binary file
frewindMove file position indicator to beginning of open file
fscanf Read data from text file
fseek
Move to specified position in file
ftell
Position in open file
fwrite Write data to binary file
Low-Level Functions for Importing Data
Low-level file I/O functions allow the most direct control over reading or writing data to a file.
However, these functions require that you specify more detailed information about your file than
the easier-to-use high-level functions. For a complete list of high-level functions and the file
formats they support, see Supported File Formats.
If the high-level functions cannot import your data, use one of the following:
fscanf, which reads formatted data in a text or ASCII file; that is, a file you can view in a text
editor. For more information, see Reading Data in a Formatted Pattern.
fgetl and fgets, which read one line of a file at a time, where a newline character separates
each line. For more information, see Reading Data Line-by-Line.
fread, which reads a stream of data at the byte or bit level. For more information, see Reading
Binary Data in a File.
Note: The low-level file I/O functions are based on functions in the ANSI® Standard C
Library. However, MATLAB® includes vectorized versions of the functions, to read and
write data in an array with minimal control loops.
Reading Binary Data in a File
As with any of the low-level I/O functions, before importing, open the file with fopen, and
obtain a file identifier. When you finish processing a file, close it with fclose(fileID).
By default, fread reads a file 1 byte at a time, and interprets each byte as an 8-bit unsigned
integer (uint8). fread creates a column vector, with one element for each byte in the file. The
values in the column vector are of class double.
For example, consider the file nine.bin, created as follows:
fid = fopen('nine.bin','w');
fwrite(fid, [1:9]);
fclose(fid);
To read all data in the file into a 9-by-1 column vector of class double:
fid = fopen('nine.bin');
col9 = fread(fid);
fclose(fid);
Changing the Dimensions of the Array
By default, fread reads all values in the file into a column vector. However, you can specify
the number of values to read, or describe a two-dimensional output matrix.
For example, to read nine.bin, described in the previous example:
fid = fopen('nine.bin');
% Read only the first six values
col6 = fread(fid, 6);
% Return to the beginning of the file
frewind(fid);
% Read first four values into a 2-by-2 matrix
frewind(fid);
two_dim4 = fread(fid, [2, 2]);
% Read into a matrix with 3 rows and
% unspecified number of columns
frewind(fid);
two_dim9 = fread(fid, [3, inf]);
% Close the file
fclose(fid);
Describing the Input Values
If the values in your file are not 8-bit unsigned integers, specify the size of the values.
For example, consider the file fpoint.bin, created with double-precision values as follows:
myvals = [pi, 42, 1/3];
fid = fopen('fpoint.bin','w');
fwrite(fid, myvals, 'double');
fclose(fid);
To read the file:
fid = fopen('fpoint.bin');
% read, and transpose so samevals = myvals
samevals = fread(fid, 'double')';
fclose(fid);
For a complete list of precision descriptions, see the fread function reference page.
Saving Memory
By default, fread creates an array of class double. Storing double-precision values in an
array requires more memory than storing characters, integers, or single-precision values.
To reduce the amount of memory required to store your data, specify the class of the array using
one of the following methods:
Match the class of the input values with an asterisk ('*'). For example, to read single-precision
values into an array of class single, use the command:
mydata = fread(fid,'*single')
Map the input values to a new class with the '=>' symbol. For example, to read uint8 values
into an uint16 array, use the command:
mydata = fread(fid,'uint8=>uint16')
For a complete list of precision descriptions, see the fread function reference page.
Reading Portions of a File
MATLAB low-level functions include several options for reading portions of binary data in a
file:
Read a specified number of values at a time, as described in Changing the Dimensions of the
Array. Consider combining this method with Testing for End of File.
Move to a specific location in a file to begin reading. For more information, see Moving within a
File.
Skip a certain number of bytes or bits after each element read. For an example, see Writing and
Reading Complex Numbers.
Testing for End of File
When you open a file, MATLAB creates a pointer to indicate the current position within the file.
Note: Opening an empty file does not move the file position indicator to the end of the
file. Read operations, and the fseek and frewind functions, move the file position
indicator.
Use the feof function to check whether you have reached the end of a file. feof returns a
value of 1 when the file pointer is at the end of the file. Otherwise, it returns 0.
For example, read a large file in parts:
filename = 'largedata.dat';
segsize = 10000;
% hypothetical file
fid = fopen(filename);
while ~feof(fid)
currData = fread(fid, segsize);
if ~isempty(currData)
disp('Current Data:');
disp(currData);
end
end
fclose(fid);
Moving within a File
To read or write selected portions of data, move the file position indicator to any location in the
file. For example, call fseek with the syntax
fseek(fid,offset,origin);
where:
fid is the file identifier obtained from fopen.
offset is a positive or negative offset value, specified in bytes.
origin specifies the location from which to calculate the position:
'bof' Beginning of file
'cof' Current position in file
'eof' End of file
Alternatively, to move easily to the beginning of a file:
frewind(fid);
Use ftell to find the current position within a given file. ftell returns the number of bytes
from the beginning of the file.
For example, create a file five.bin:
A = 1:5;
fid = fopen('five.bin','w');
fwrite(fid, A,'short');
fclose(fid);
Because the call to fwrite specifies the short format, each element of A uses two storage
bytes in five.bin.
Reopen five.bin for reading:
fid = fopen('five.bin','r');
Move the file position indicator forward 6 bytes from the beginning of the file:
status = fseek(fid,6,'bof');
Read the next element:
four = fread(fid,1,'short');
The act of reading advances the file position indicator. To determine the current file position
indicator, call ftell:
position = ftell(fid)
position =
8
To move the file position indicator back 4 bytes, call fseek again:
status = fseek(fid,-4,'cof');
Read the next value:
three = fread(fid,1,'short');
Reading Files Created on Other Systems
Different operating systems store information differently at the byte or bit level:
Big-endian systems store bytes starting with the largest address in memory (that is, they start
with the big end).
Little-endian systems store bytes starting with the smallest address (the little end).
Windows® systems use little-endian byte ordering, and UNIX® systems use big-endian byte
ordering.
To read a file created on an opposite-endian system, specify the byte ordering used to create the
file. You can specify the ordering in the call to open the file, or in the call to read the file.
For example, consider a file with double-precision values named little.bin, created on a
little-endian system. To read this file on a big-endian system, use one (or both) of the following
commands:
Open the file with
fid = fopen('little.bin', 'r', 'l')
Read the file with
mydata = fread(fid, 'double', 'l')
where 'l' indicates little-endian ordering.
If you are not sure which byte ordering your system uses, call the computer function:
[cinfo, maxsize, ordering] = computer
The returned ordering is 'L' for little-endian systems, or 'B' for big-endian systems.
Opening Files with Different Character Encodings
Encoding schemes support the characters required for particular alphabets, such as those for
Japanese or European languages. Common encoding schemes include US-ASCII or UTF-8.
The encoding scheme determines the number of bytes required to read or write char values. For
example, US-ASCII characters always use 1 byte, but UTF-8 characters use up to 4 bytes.
MATLAB automatically processes the required number of bytes for each char value based on
the specified encoding scheme. However, if you specify a uchar precision, MATLAB
processes each byte as uint8, regardless of the specified encoding.
If you do not specify an encoding scheme, fopen opens files for processing using the default
encoding for your system. To determine the default, open a file, and call fopen again with the
syntax:
[filename, permission, machineformat, encoding] = fopen(fid);
If you specify an encoding scheme when you open a file, the following functions apply that
scheme: fscanf, fprintf, fgetl, fgets, fread, and fwrite.
MAT lab Graphics
Types of MATLAB Plots
The following two tables classify and illustrate the kinds of plots you can create with
MATLAB®. They include line, bar, area, direction and vector field, radial, and scatter graphs.
Two-Dimensional Plotting Functions
This table shows MATLAB 2-D plotting functions. Click any icon to see the documentation for
that function. Techniques for using many of the functions are also discussed in later sections of
this document.
Line
Graphs
Bar Graphs
plot
bar (grouped) area
plotyy
barh
(grouped)
loglog
bar (stacked) fill
semilogx
barh
(stacked)
contourf
semilogy
hist
image
stairs
pareto
pcolor
contour
errorbar
ezcontourf
ezplot
stem
ezcontour
Area Graphs Direction
Graphs
pie
Radial
Graphs
Scatter
Graphs
feather
polar
scatter
quiver
rose
spy
comet
compass
plotmatrix
ezpolar
Line
Graphs
Bar Graphs
Area Graphs Direction
Graphs
Radial
Graphs
Scatter
Graphs
Three-Dimensional Plotting Functions
This table shows MATLAB 3-D and volume plotting functions. Some functions generate 3-D
data (cylinder, ellipsoid, sphere) that you can use to generate geometric shapes on
which you can superimpose your data. Click any picture in the table to see the documentation for
that function.
Line Graphs
Mesh
Graphs
and Bar
Graphs
Area Graphs
and
Constructive
Objects
Surface
Graphs
Direction
Graphs
Volumetric
Graphs
plot3
mesh
pie3
surf
quiver3
scatter3
contour3
meshc
fill3
surfl
comet3
coneplot
contourslice meshz
patch
surfc
streamslice streamline
ezplot3
ezmesh
cylinder
ezsurf
streamribbon
waterfall
stem3
ellipsoid
ezsurfc
streamtube
bar3
sphere
Line Graphs
Mesh
Graphs
and Bar
Graphs
Area Graphs
and
Constructive
Objects
Surface
Graphs
Direction
Graphs
Volumetric
Graphs
bar3h
Multiple plots – Style options – Sub plots
The MATLAB environment offers a variety of data plotting functions plus a set of GUI tools to
create, and modify graphic displays. The GUI tools afford most of the control over graphic
properties and options that typed commands such as annotate, get, and set provide.
A figure is a MATLAB window that contains graphic displays (usually data plots) and UI
components. You create figures explicitly with the figure function, and implicitly whenever
you plot graphics and no figure is active. By default, figure windows are resizable and include
pull-down menus and toolbars.
A plot is any graphic display you can create within a figure window. Plots can display tabular
data, geometric objects, surface and image objects, and annotations such as titles, legends, and
colorbars. Figures can contain any number of plots. Each plot is created within a 2-D or a 3-D
data space called an axes. You can explicitly create axes with the axes or subplot functions.
A graph is a plot of data within a 2-D or 3-D axes. Most plots made with MATLAB functions
and GUIs are therefore graphs. When you graph a one-dimensional variable (e.g.,
rand(100,1)), the indices of the data vector (in this case 1:100) become assigned as x
values, and plots the data vector as y values. Some types of graphs can display more than one
variable at a time, others cannot.
The contents and varieties of figures, plots and graphs that MATLAB can make are explained in
the following sections.
Note: All the figures are generated on a Windows® system, the placement of the toolbar
and menu options can vary for other operating systems.
Anatomy of a Graph
MATLAB plotting functions and tools direct their output to a figure window. Each figure is a
separate window that you can dock in the desktop, and collect together with other plots in a
Figure Group. To illustrate the basic components of a graph, execute the following code to
create a plot of a family of sine curves:
x = 0:.2:20;
y = sin(x)./sqrt(x+1);
y(2,:) = sin(x/2)./sqrt(x+1);
y(3,:) = sin(x/3)./sqrt(x+1);
plot(x,y)
The resulting figure contains a 2-D set of axes. This graphic identifies the components and tools
of a figure window.
The plot function uses a default line style and color to distinguish the data sets plotted in the
graph. You can change the appearance of these graphic components or add annotations to the
graph to present your data in a particular way.
Figure Toolbars
Figure toolbars provide shortcuts to access commonly used features. These include operations
such as saving and printing, plus tools for interactive zooming, panning, rotating, querying, and
editing plots. The following picture shows the features available from this toolbar.
You can enable two other toolbars from the View menu:
Camera Toolbar — Use for manipulating 3-D views. See View Control with the Camera Toolbar
in the MATLAB 3-D Visualization documentation for more information.
Plot Edit Toolbar — Use for annotation and setting object properties. See Annotation Tools on
the Plot Edit Toolbar for more information.
3D Graphics in MATLAB
We'll introduce different types of plotting in 3D.
MATLAB has different plotting a
pproaches for showing data in
3D:
3D line plots
[MATLAB:
plot3
. Plot lines in 3-space]
3D mesh plots
[MATLAB:
mesh, meshc, meshz, waterfall
.
Make wire-framed surfaces 3D]
3D surface plots
[MATLAB:
surf, shading, surfc, surfl,
surfnorm
,
. Like mesh, with patches filled in with color]
3D contour plots
[MATLAB:
contour, contour3, contourf,
shading, clabel
. Contour plots in 2 & 3D]
3D volume plots
[MATLAB:
slice, isosurface, smooth3,
isocaps, isonormals
. Visualizations of fully 3D data sets]
3D specialized plots
[MATLAB:
ribbon, quiver, quiver3, fill3,
stem3, sphere, cylinder
. Special purpose 3D plotting]
There are many other MATLAB functions that relate to these
renderings, including
camera and lighting attributes
.
3D LINE PLOTS
plot3
Plot lines and points in 3-D space
PLOT3()
is a three-dimensional analogue of PLOT().
PLOT3(x,y,z),
where x, y and z are three
vectors
of the same
length, plots a line in 3-space through the points whose
coordinates are the elements of x, y and z.
PLOT3(X,Y,Z),
where X, Y and Z are three
matrices
of the
same size, plots several lines obtained from the columns of X,
Y and Z.
Various
line types,
plot symbols and
colors
may be obtained with PLOT3(X,Y,Z,s)
where
s is a 1, 2 or 3
character string
made from the characters listed under the
PLOT command.
PLOT3(x1,y1,z1,s1,x2, y2,
z2, s2, x3, y3, z3, s3,...)
combines the
plots defined by the (x,y,z,s) fourtuples, where the x's, y's and
z's are
vectors or matrices and the s's are strings
.
helix1.m
t = linspace(0,10*pi); %100 points between 0-10Pi
plot3
(sin(t),cos(t),t)
xlabel('sin(t)'), ylabel('cos(t)'), zlabel('t')
text(0,0,0,'Origin')
grid on
title('A Helix! ')
Ex:
Less points
more points
diff functions
Azimuth and Elevation
The view command specifies the viewpoint by defining azimuth and elevation with respect to the
axis origin.
x-y plane
, with positive angles
indicating counter-clockwise rotation of the viewpoint.
Elevation
is the angle above (positive angle) or below (negative
angle) the
x-y plane
VIEW
3-D graph viewpoint specification.
VIEW(AZ,EL) and VIEW([AZ,EL])
set the angle of the view from which an observer sees the
current 3-D plot. AZ is the azimuth or horizontal rotation and EL is the vertical elevation
Some examples:
AZ = -37.5, EL = 30 is the default 3-D view.
AZ = 0, EL = 90 is directly overhead and the default 2-D
view.
AZ = EL = 0 looks directly up the first column of the matrix.
AZ = 180 is behind the matrix.
VIEW(2) sets the default 2-D view, AZ = 0, EL = 90.
VIEW(3) sets the default 3-D view, AZ = -37.5, EL = 30.
[AZ,EL] = VIEW returns the current azimuth and elevation.
helix2.m
clf %clear figure window
plot3
(sin(t),cos(t),t)
xlabel('X=sin(t)'), ylabel('Y=cos(t)'),
zlabel('Z=t')
grid on
title('Helix: 3D view')
subplot(2,2,2)
plot3
(sin(t),cos(t),t),view(0,90)
xlabel('X=sin(t)'), ylabel('Y=cos(t)'),
zlabel('Z=t')
title('View just the X,Y plane')
subplot(2,2,3)
plot3
(sin(t),cos(t),t),view(0,0)
xlabel('X=sin(t)'), ylabel('Y=cos(t)'),
zlabel('Z=t')
title('View just the X,Z plane')
subplot(2,2,4)
plot3
(sin(t),cos(t),t,'r'),view(90,0),grid
xlabel('X=sin(t)'), ylabel('Y=cos(t)'),
zlabel('Z=t')
title('View just the Y,Z plane')
sine.m
clf %clear figure window
x = linspace(0,3*pi); % x-axis data
z1 = sin(x); % plot in x-z plane
z2 = sin(2*x);
z3 = sin(3*x);
y1 = zeros(size(x)); % spread out along y-axes
y3 = ones(size(x)); % by giving each curve
different y-axis values
y2 = y3/2;
plot3
(x,y1,z1,x,y2,z2,x,y3,z3)
grid on
xlabel('X-axis'), ylabel('Y-axis'), zlabel('Zaxis')
title('sin(x), sin(2x), sin(3x)')
pause
plot3
(x,z1,y1,x,z2,y2,x,z3,y3)
grid on
xlabel('X-axis'), ylabel('Y-axis'), zlabel('Zaxis')
title('sin(x), sin(2x), sin(3x)')
Representing a Matrix as a Surface
MATLAB defines a surface by the z-coordinates of points above a rectangular grid in the x-y
plane. The plot is formed by joining adjacent points with straight lines
Surface plots are useful for visualizing matrices that are too large to display in numerical
form and for graphing functions of two variables. MATLAB can create different forms of
surface plots. Mesh plots are wire-frame surfaces that color only the lines connecting the
defining points. Surface plot display both the connecting lines and the faces of the surface
in color. Mesh and Surface Plots The mesh and surf commands create 3-D surface plots of
matrix data.
If Z is a matrix for which the elements Z(i,j) define the height of a surface over an underlying
(i,j) grid, then mesh(Z) generates a colored, wire-frame view of the surface and displays it in a 3D view. For example :
x=
12 -1 55
34 -1 66
-123 3 56
>> mesh(x)
if X, Y, Z, and C are matrices of the
same dimensions, then mesh(X,Y,Z,C) describes a mesh surface with vertices
having color C(i,j) and located at the points (X(i,j), Y(i,j), Z(i,j))
UNIT –IV
Control Structures
MATLAB: Control Structures- loops
In MATLAB we will use the while and for loops. They are very similar to
the ones which you may have learned in C++. The following tables illustrate
the similarities/differences:
while structure in C++
while( fabs(dx) > 0.0001)
{
fprime = 3*pow(x,2) - 5;
f = pow(x,3) 5 * x + 3;
dx = f / fprime;
x = x dx;
}
while structure in
MATLAB
Differences
while( abs(dx) > 0.0001) Use abs for
absolute value
fprime = 3*x^2 - 5;
No need for
f = x ^ 3 5 * x +3;
brackets end
plays the role of
dx = f / fprime;
the bracket
x = x dx;
no need for pow
end
function, use ^ for
exponent.
The following pictures illustrate a complete program in MATLAB which
utilizes the above segment. The condition is slightly different to make sure
the program does not fall into an infinite loop.
The results are shown here:
In the while structure, another difference between C++ and MATLAB is
that the condition of while may be actually a condition on arrays. The
following example illustrates this in a very simple way:
we see that as soon one of the components of the array evaluates to false, the
loop terminates.
-------------------------------------------------------------------------------------------------------------------------------------------
We can now study the for structure. The following table illustrates the
similarities/differences:
for structure in C++
for structure in
MATLAB
Differences
for( k = 1; k <=10;
k++)
for k = 1:1:10
k=start:increment:end
factorial = factorial * k; (if the increment is not
{
specified is taken as 1)
fprintf(‘ %i %i’,
factorial = factorial * k; k,factorial);
No need for brackets end
plays the role of the
cout << k <<”
“<< end
bracket
factorial;
}
The following pictures show the complete .m file and the results of running
it in MATLAB.
Again in the for structure, another difference between C++ and MATLAB
is that the for index may be actually set equal to a matrix. Then the loop
starts by using as index the first column of the array, then the second column
etc. until the last column is used.
The following example illustrates this in a very simple way:
Mat Lab –Editor
edit
Edit or create file
Syntax
edit example
edit file example
edit file1 ... fileN example
Description
example
edit opens a new file called Untitled in the Editor. MATLAB® does not automatically save
Untitled.
example
edit file opens the specified file in the Editor. If file does not already exist, MATLAB
asks if you want to create it. file can include a partial path, complete path, relative path, or no
path. You must have write permission to the path to create file, otherwise, MATLAB ignores
the argument.
You must specify the extension to open .mat and .mdl files. MATLAB cannot directly edit
binary files, such as .p and .mex files.
example
edit file1 ... fileN opens each file, file1 ... fileN, in the Editor.
Function subprograms in MAT lab
Subfunctions in Matlab
Up to this point, our programs have been fairly simple, usually taking on
a single task, such as solving a quadratic equation. As programs become more complex and
perform multiple tasks, modern programmers break programs into a series of self contained
modules. In this manner, various parts of the program can be written separately, tested, and once
stable, can be integrated into the program as a whole. In older programming languages, these
modules were known as subroutines. In modern, object oriented languages such as C++ and
Java, the modules are objects, created from classes, that contain their own variables and methods
for
manipulating data and performing tasks. These objects can then be reused and assembled to
create sophisticated programs. To attack a complex programming task in Matlab, we must rst
break the
task up into manageable units. Each of these units or modules are then coded as functions and
tested until we are certain they perform the simple task for which they are designed. Once satised
that the individual functions are performing as designed, we must then integrate them into a
complete and functioning program. In this section we will discuss two ways that we can
accomplish this modular design.
1. We can write each of the modules as functions in separate les. We then write a master script le
which calls each of the function M-les as needed.
2. We can write a primary function in place of the script le. We can then
incorporate the modules as subfunctions
directly in this primary function That is, we write one self contained le.
Actually there is also a third way to proceed. We can write a primary le
in place of a script However, by signalling the end of this primary function
with the Matlab keyword end , we signal Matlab that out subfunctions (each of which must also
use the keyword end ) are nested functions . A primary function written in this manner emulates
some of the behavior of an object in an object oriented language, with its own variables and
methods (subfunctions). We’ll see in a later section that the rules for variable scope will change
signicantly when using nested functions.
We will investigate each of these options in some detail. In the next section,
we investigate the rst of these options, calling a function M-le from within the body of a script
Calling Functions From Script Files
We are going to tackle a programmng project that will perform rational arithmetic for the user of
the program. Options will include reducing, adding, subtracting, multiplying, and dividing
fractions input by the user of our program. Contemplating the design of such a program, here are
some possible smaller tasks that need implmentation.
1. Present the user with a menu of choices: reduction, addition, subtraction,
multiplication, and division.
2. Routines will need to be written for each possible user choice on the menu.
3. The program will need to query the user for a menu choice, then react in the appropriate
manner.
Note that this design is preliminary. In the process of writing a complex
program, di-culties with the original design will surely arise. When that occurs, we will need to
make modications of the original design, which in turn will create the need for design of new
modules not considered in the design. However, one clear place that we can start is on the design
of a menu of choices for the user of our program. Remember, the menu should query what action
the user wants to perform, reduction, addition, subtraction, or division. With this thought in
mind, we write the following lines and save the script as rationalArithmetic.m
.
fprintf(’Rational Arithmetic Menu:\n\n’)
fprintf(’1). Reduce a fraction to lowest terms.\n’)
fprintf(’2). Add two fractions.\n’)
fprintf(’3). Subtract two fractions.\n’)
fprintf(’4). Multiply two fractions.\n’)
fprintf(’5). Divide two fractions.\n’)
fprintf(’6). Exit program.\n\n’)
n=input(’Enter number of your choice: ’);
Go to the Matlab prompt in the command window and execute the script
MAT LAB Programming
MATLAB is a programming language developed by MathWorks. It started out as a matrix
programming language where linear algebra programming was simple. It can be run both under
interactive sessions and as a batch job.
Most MATLAB scripts and functions can be run in the open source programme octave. This is
freely available for most computing platforms.
GNU Octave and LabVIEW MathScript are systems for numerical computations with an m-file
script language that is mostly compatible with MATLAB. Both alternatives can replace
MATLAB in many circumstances. While a good deal of the content of this book will also apply
to both Octave and LabVIEW MathScript, it is not guaranteed to work in exactly the same
manner. Differences and comparison between MATLAB and Octave are presented in Comparing
Octave and MATLAB.
Basic MATLAB Concepts
Saving and loading a MAT-file
Commands
File Naming conventions
Basic Reading and Writing data from a file
The MATLAB Command Prompt
Calculator
Data Storage and Manipulation
Data Types and Operators on Point Values
Boolean and Rational
Strings
Portable Functions
Complex Numbers
Arrays and Matrices
What is an array?
Introduction to array operations
Vectors and Basic Vector Operations
Mathematics with Vectors and Matrices
Struct Arrays
Cell Arrays
Sparse Matrices
Graphics
Graphics
Plot
Polar Plot
Mesh
Semilogx or Semilogy
Loglog
Bode Plot
Nichols Plot
Nyquist Plot
Handle Graphics
What is a handle?
Figure handles
Axis handles
Other types of handles
Annotating Plots
Inserting Newlines into Plot Labels
M-file Programming
Scripts
Comments
The Input Function
Control Flow
Loops and Branches
Error Messages
MATLAB Caveats
Inserting Newlines into Disp Warn and Error
Debugging M Files
Numerical Manipulation
Linear Algebra
Differential Equations
Ordinary Differential Equations
Partial Differential Equations
More advanced I/O
Different versions of MATLAB handle this differently. We will focus on versions 6.5 and 7.x,
primarily on MATLAB 7.x since it is the latest. A note will appear when the procedure is
different for ver. 6.
Reading and writing from files
Writing and Reading to A Serial Port
Writing to a USB port
Examples
Filtering
Controls
Phase vocoder
See "Phase vocoder and encoder in MATLAB" for an example phase vocoder and the
corresponding sound sample encoder in MATLAB.
Object Oriented Programming
MATLAB as well as Octave have object oriented capabilities. Yet, technically it is not fully an
object oriented language.
An Object Oriented Language(OOL) has three components: 1. Polymorphism 2. Inheritance 3.
Encapsulation
Octave can be extended by adding new objects. Those objects can overload the operators like
e.g. assignment, slicing, comparison.
While in MATLAB, this can be done with m-script, in Octave new objects are implemented as
C++ classes. A simple example of how objects can be added to Octave can be found here.
Struct arrays
MATLAB classes
The most important differences between Octave and MATLAB that anyone willing to use
Octave instead of MATLAB should be aware of.
Toolboxes and Extensions
The toolboxes are pretty good if you can afford them. In version 7 there are a lot of toolboxes.
Symbolic Toolbox
Image Processing Toolbox
MATLAB Compiler
Legacy Toolboxes
GUIDE
allows the creation of interactive user interfaces.
Simulink is for modeling, simulating and analysing systems.
Psychtoolbox
is a set of tools that aid in vision research.
Distributed computing- The distributed computing toolbox is a set of tools that aid in distributing
models over a cluster.
Optimization- The optimization toolbox includes various algorithms for minimization.
Matlab in medicine
„Image Processing in Optical Coherence Tomography using Matlab” is a book which will
introduce you to subtleties related to the implementation of selected fragments of algorithms, the
notation of some of them in the Matlab environment has been given. The presented source code
is shown only in the form of example of implementable selected algorithm. The book is
addressed to ophthalmologists , IT specialists and students involved in the development of
applications designed for automation of measurements for the needs of medicine.
Types of Functions
Local and Nested Functions in a File
Program files can contain multiple functions: the main function and any combination of local or
nested functions. Local and nested functions are useful for dividing programs into smaller tasks,
making it easier to read and maintain your code.
Local functions are subroutines that are available to any other functions within the same file.
They can appear in the file in any order after the main function in the file. Local functions are the
most common way to break up programmatic tasks.
For example, create a single program file named myfunction.m that contains a main function,
myfunction, and two local functions, squareMe and doubleMe:
function b = myfunction(a)
b = squareMe(a) + doubleMe(a);
end
function y = squareMe(x)
y = x.^2;
end
function y = doubleMe(x)
y = x.*2;
end
You can call the main function from the command line or another program file, although the
local functions are only available to myfunction:
myfunction(pi)
ans =
16.1528
Nested functions are completely contained within another function. The primary difference
between nested functions and local functions is that nested functions can use variables defined in
parent functions without explicitly passing those variables as arguments.
Nested functions are useful when subroutines share data, such as GUI applications that pass data
between components. For example, create a function that allows you to set a value between 0 and
1 using either a slider or an editable text box. If you use nested functions for the callbacks, the
slider and text box can share the value and each other's handles without explicitly passing them:
function myslider
value = 0;
f = figure;
s = uicontrol(f,'Style','slider','Callback',@slider);
e = uicontrol(f,'Style','edit','Callback',@edittext,...
'Position',[100,20,100,20]);
function slider(obj,~)
value = get(obj,'Value');
set(e,'String',num2str(value));
end
function edittext(obj,~)
value = str2double(get(obj,'String'));
set(s,'Value',value);
end
end
For more information, see:
Local Functions
Nested Functions
Private Functions in a Subfolder
Like local or nested functions, private functions are accessible only to functions in a specific
location. However, private functions are not in the same file as the functions that can call them.
Instead, they are in a subfolder named private. Private functions are available only to
functions in the folder immediately above the private folder. Use private functions to separate
code into different files, or to share code between multiple, related functions.
For more information, see Private Functions.
Anonymous Functions Without a File
Anonymous functions allow you to define a function without creating a program file, as long as
the function consists of a single statement. A common application of anonymous functions is to
define a mathematical expression, and then evaluate that expression over a range of values using
a MATLAB® function function—a function that accepts a function handle as an input.
For example, this statement creates a function handle named s for an anonymous function:
s = @(x) sin(1./x);
This function has a single input, x. The @ operator creates the function handle.
You can use the function handle to evaluate the function for particular values, such as
y = s(pi)
y=
0.3130
Or, you can pass the function handle to a function that evaluates over a range of values, such as
fplot:
range = [0.01,0.1];
fplot(s,range)
FUNCTION_HANDLING
Handle used in calling functions indirectly
Syntax
handle = @functionname
handle = @(arglist)anonymous_function
Description
handle = @functionname returns a handle to the specified MATLAB® function.
A function handle is a MATLAB value that provides a means of calling a function indirectly.
You can pass function handles in calls to other functions (often called function functions). You
can also store function handles in data structures for later use (for example, as Handle Graphics
callbacks). A function handle is one of the standard MATLAB data types.
At the time you create a function handle, the function you specify must be on the MATLAB path
and in the current scope of the code creating the handle. For example, you can create a handle to
a local function as long as you do so from within the file that defines that local function. This
condition does not apply when you evaluate the function handle. You can, for example, execute a
local function from a separate (out-of-scope) file using a function handle. This requires that the
handle was created by the local function (in-scope).
handle = @(arglist)anonymous_function constructs an anonymous function and
returns a handle to that function. The body of the function, to the right of the parentheses, is a
single MATLAB statement or command. arglist is a comma-separated list of input
arguments. Execute the function by calling it by means of the function handle, handle.
Examples
Example 1 — Constructing a Handle to a Named Function
The following example creates a function handle for the humps function and assigns it to the
variable fhandle.
fhandle = @humps;
Pass the handle to another function in the same way you would pass any argument. This example
passes the function handle just created to fminbnd, which then minimizes over the interval
[0.3, 1].
x = fminbnd(fhandle, 0.3, 1)
x=
0.6370
The fminbnd function evaluates the @humps function handle. A small portion of the
fminbnd file is shown below. In line 1, the funfcn input parameter receives the function
handle @humps that was passed in. The statement, in line 113, evaluates the handle.
1
function [xf,fval,exitflag,output] = ...
fminbnd(funfcn,ax,bx,options,varargin)
.
.
.
113 fx = funfcn(x,varargin{:});
Example 2 — Constructing a Handle to an Anonymous Function
The statement below creates an anonymous function that finds the square of a number. When
you call this function, MATLAB assigns the value you pass in to variable x, and then uses x in
the equation x.^2:
sqr = @(x) x.^2;
The @ operator constructs a function handle for this function, and assigns the handle to the output
variable sqr. As with any function handle, you execute the function associated with it by
specifying the variable that contains the handle, followed by a comma-separated argument list in
parentheses. The syntax is
fhandle(arg1, arg2, ..., argN)
To execute the sqr function defined above, type
a = sqr(5)
a=
25
Because sqr is a function handle, you can pass it in an argument list to other functions. The
code shown here passes the sqr anonymous function to the MATLAB integral function to
compute its integral from zero to one:
integral(sqr, 0, 1)
ans =
0.3333
Example 3 — Using an Array of Function Handles
This example creates a structure array of function handles S and then applies each handle in the
array to the output of a linspace calculation in one operation using structfun:
S.a = @sin; S.b = @cos; S.c = @tan;
structfun(@(x)x(linspace(1,4,3)), S, 'UniformOutput', false)
ans =
a: [0.8415 0.5985 -0.7568]
b: [0.5403 -0.8011 -0.6536]
c: [1.5574 -0.7470 1.1578]
Errors and Warnings
MATLAB® Code Analyzer can automatically check your code for coding problems, as described
in the following sections:
Automatically Check Code in the Editor — Code Analyzer
You can view warning and error messages about your code, and modify your file based on the
messages. The messages update automatically and continuously so you can see if your changes
addressed the issues noted in the messages. Some messages offer additional information,
automatic code correction, or both.
To use continuous code checking in a MATLAB code file in the Editor:
On the Home tab, in the Environment section, click
Preferences.
Select Code Analyzer, and then select the Enable integrated warning and error messages
check box.
Set the Underlining option to Underline warnings and errors, and then click OK.
Open a MATLAB code file in the Editor. This example uses the sample file lengthofline.m
that ships with the MATLAB software:
Open the example file:
open(fullfile(matlabroot,'help','techdoc','matlab_env',...
'examples','lengthofline.m'))
Save the example file to a folder to which you have write access. For the example,
lengthofline.m is saved to C:\my_MATLAB_files.
Examine the message indicator at the top of the message bar to see the Code Analyzer messages
reported for the file:
Red indicates syntax errors were detected. Another way to detect some of these errors is using
syntax highlighting to identify unterminated strings, and delimiter matching to identify
unmatched keywords, parentheses, braces, and brackets.
Orange indicates warnings or opportunities for improvement, but no errors, were detected.
Green indicates no errors, warnings, or opportunities for improvement were detected.
In this example, the indicator is red, meaning that there is at least one error in the file.
Click the message indicator to go to the next code fragment containing a message. The next code
fragment is relative to the current cursor position, viewable in the status bar.
In the lengthofline example, the first message is at line 22. The cursor moves to the
beginning of line 22.
The code fragment for which there is a message is underlined in either red for errors or orange
for warnings and improvement opportunities.
View the message by moving the mouse pointer within the underlined code fragment.
The message opens in a tooltip and contains a Details button that provides access to additional
information by extending the message. Not all messages have additional information.
Click the Details button.
The window expands to display an explanation and user action.
Modify your code, if needed.
The message indicator and underlining automatically update to reflect changes you make, even if
you do not save the file.
On line 28, hover over prod.
The code is underlined because there is a warning message, and it is highlighted because an
automatic fix is available. When you view the message, it provides a button to apply the
automatic fix.
Fix the problem by doing one of the following:
If you know what the fix is (from previous experience), click Fix.
If you are unfamiliar with the fix, view, and then apply it as follows:
Right-click the highlighted code (for a single-button mouse, press Ctrl+ click), and then view the
first item in the context menu.
Click the fix.
MATLAB automatically corrects the code.
In this example, MATLAB replaces prod(size(hline)) with numel(hline).
Go to a different message by doing one of the following:
To go to the next message, click the message indicator or the next underlined code fragment.
To go to a line that a marker represents, click a red or orange line in the indicator bar .
To see the first error in lengthofline, click the first red marker in the message bar. The
cursor moves to the first suspect code fragment in line 48. The Details and Fix buttons are
dimmed, indicating that there is no more information about this message and there is no
automatic fix.
Multiple messages can represent a single problem or multiple problems. Addressing one might
address all of them, or after addressing one, the other messages might change or what you need
to do might become clearer.
Modify the code to address the problem noted in the message—the message indicators update
automatically.
The message suggests a delimiter imbalance on line 48. You can investigate that as follows:
On the Home tab, in the Environment section, click
Preferences.
Select Keyboard.
Under Delimiter Matching, select Match on arrow key, and then click OK.
In the Editor, move the arrow key over each of the delimiters to see if MATLAB indicates a
mismatch.
In the example, it might appear that there are no mismatched delimiters. However, code analysis
detects the semicolon in parentheses: data{3}(;), and interprets it as the end of a statement.
The message reports that the two statements on line 48 each have a delimiter imbalance.
In line 48, change data{3}(;) to data{3}(:).
Now, the underline no longer appears in line 48. The single change addresses the issues in both
of the messages for line 48.
Because the change removed the only error in the file, the message indicator at the top of the bar
changes from red to orange, indicating that only warnings and potential improvements remain.
After modifying the code to address all the messages, or disabling designated messages, the
message indicator becomes green. The example file with all messages addressed has been saved
as lengthofline2.m. Open the corrected example file with the command:
open(fullfile(matlabroot,'help','techdoc',...
'matlab_env', 'examples','lengthofline2.m'))
Create a Code Analyzer Message Report
You can create a report of messages for an individual file, or for all files in a folder, using one of
these methods:
Run a report for an individual MATLAB code file:
On the Editor window, click
.
Select Show Code Analyzer Report.
A Code Analyzer Report appears in the MATLAB Web Browser.
Modify your file based on the messages in the report.
Save the file.
Rerun the report to see if your changes addressed the issues noted in the messages.
Run a report for all files in a folder:
On the Current Folder browser, click
.
Select Reports > Code Analyzer Report.
Modify your files based on the messages in the report.
For details, see MATLAB Code Analyzer Report.
Save the modified file(s).
Rerun the report to see if your changes addressed the issues noted in the messages.
Adjust Code Analyzer Message Indicators and Messages
Depending on the stage at which you are in completing a MATLAB file, you might want to
restrict the code underlining. You can do this by using the Code Analyzer preference referred to
in step 1, in Check Code for Errors and Warnings. For example, when first coding, you might
prefer to underline only errors because warnings would be distracting.
Code analysis does not provide perfect information about every situation and in some cases, you
might not want to change the code based on a message. If you do not want to change the code,
and you do not want to see the indicator and message for that line, suppress them. For the
lengthofline example, in line 49, the first message is Terminate statement with
semicolon to suppress output (in functions). Adding a semicolon to the end
of a statement suppresses output and is a common practice. Code analysis alerts you to lines that
produce output, but lack the terminating semicolon. If you want to view output from line 49, do
not add the semicolon as the message suggests.
There are a few different ways to suppress (turn off) the indicators for warning and error
messages:
Suppress an Instance of a Message in the Current File
Suppress All Instances of a Message in the Current File
Suppress All Instances of a Message in All Files
Save and Reuse Code Analyzer Message Settings
You cannot suppress error messages such as syntax errors. Therefore, instructions on suppressing
messages do not apply to those types of messages.
Suppress an Instance of a Message in the Current File
You can suppress a specific instance of a Code Analyzer message in the current file. For
example, using the code presented in Check Code for Errors and Warnings , follow these steps:
In line 49, right-click at the first underline (for a single-button mouse, press Ctrl+click).
From the context menu, select Suppress 'Terminate statement with semicolon...' > On This
Line.
The comment %#ok<NOPRT> appears at the end of the line, which instructs MATLAB not to
check for a terminating semicolon at that line. The underline and mark in the indicator bar for
that message disappear.
If there are two messages on a line that you do not want to display, right-click separately at each
underline and select the appropriate entry from the context menu.
The %#ok syntax expands. For the example, in the code presented in Check Code for Errors and
Warnings, ignoring both messages for line 49 adds %#ok<NBRAK,NOPRT>.
Even if Code Analyzer preferences are set to enable this message, the specific instance of the
message suppressed in this way does not appear because the %#ok takes precedence over the
preference setting. If you later decide you want to check for a terminating semicolon at that line,
delete the %#ok<NOPRT> string from the line.
Suppress All Instances of a Message in the Current File
You can suppress all instances of a specific Code Analyzer message in the current file. For
example, using the code presented in Check Code for Errors and Warnings, follow these steps:
In line 49, right-click at the first underline (for a single-button mouse, press Ctrl+click).
From the context menu, select Suppress 'Terminate statement with semicolon...' > In This
File.
The comment %#ok<*NOPRT> appears at the end of the line, which instructs MATLAB to not
check for a terminating semicolon throughout the file. All underlines, as well as marks in the
message indicator bar that correspond to this message disappear.
If there are two messages on a line that you do not want to display anywhere in the current file,
right-click separately at each underline, and then select the appropriate entry from the context
menu. The %#ok syntax expands. For the example, in the code presented in Check Code for
Errors and Warnings, ignoring both messages for line 49 adds %#ok<*NBRAK,*NOPRT>.
Even if Code Analyzer preferences are set to enable this message, the message does not appear
because the %#ok takes precedence over the preference setting. If you later decide you want to
check for a terminating semicolon in the file, delete the %#ok<*NOPRT> string from the line.
Suppress All Instances of a Message in All Files
You can disable all instances of a Code Analyzer message in all files. For example, using the
code presented in Check Code for Errors and Warnings, follow these steps:
In line 49, right-click at the first underline (for a single-button mouse, press Ctrl+click).
From the context menu, select Suppress 'Terminate statement with semicolon...' > In All
Files.
This modifies the Code Analyzer preference setting.
If you know which message or messages you want to suppress, you can disable them directly
using Code Analyzer preferences, as follows:
On the Home tab, in the Environment section, click
Select Code Analyzer.
Preferences.
Search the messages to find the ones you want to suppress.
Clear the check box associated with each message you want to suppress in all files.
Click OK.
Save and Reuse Code Analyzer Message Settings
You can specify that you want certain Code Analyzer messages enabled or disabled, and then
save those settings to a file. When you want to use a settings file with a particular file, you select
it from the Code Analyzer preferences pane. That setting file remains in effect until you select
another settings file. Typically, you change the settings file when you have a subset of files for
which you want to use a particular settings file.
Follow these steps:
On the Home tab, in the Environment section, click
Preferences.
The Preferences dialog box opens.
Select Code Analyzer.
Enable or disable specific messages, or categories of messages.
Click the Actions button
, select Save as, and then save the settings to a txt file.
Click OK.
You can reuse these settings for any MATLAB file, or provide the settings file to another user.
To use the saved settings:
On the Home tab, in the Environment section, click
Preferences.
The Preferences dialog box opens.
Select Code Analyzer.
Use the Active Settings drop-down list to select Browse....
The Open dialog box appears.
Choose from any of your settings files.
The settings you choose are in effect for all MATLAB files until you select another set of Code
Analyzer settings.
Understand Code Containing Suppressed Messages
If you receive code that contains suppressed messages, you might want to review those messages
without the need to unsuppress them first. A message might be in a suppressed state for any of
the following reasons:
One or more %#ok<message-ID> directives are on a line of code that elicits a message
specified by <message-ID>.
One or more %#ok<*message-ID> directives are in a file that elicits a message specified by
<message-ID>.
It is cleared in the Code Analyzer preferences pane.
It is disabled by default.
To determine the reasons why some messages are suppressed:
Search the file for the %#ok directive and create a list of all the message IDs associated with that
directive.
On the Home tab, in the Environment section, click
Preferences.
The Preferences dialog box opens.
Select Code Analyzer.
In the search field, type msgid: followed by one of the message IDs, if any, you found in step
1.
The message list now contains only the message that corresponds to that ID. If the message is a
hyperlink, click it to see an explanation and suggested action for the message. This can provide
insight into why the message is suppressed or disabled. The following image shows how the
Preferences dialog box appears when you enter msgid:CPROP in the search field.
Click the
button to clear the search field, and then repeat step 4 for each message ID you
found in step 1.
Display messages that are disabled by default and disabled in the Preferences pane by clicking
the down arrow to the right of the search field. Then, click Show Disabled Messages.
Review the message associated with each message ID to understand why it is suppressed in the
code or disabled in Preferences.
Errors and warnings – Matlab debugger
Code analysis is a valuable tool, but there are some limitations:
Sometimes, it fails to produce Code Analyzer messages where you expect them.
By design, code analysis attempts to minimize the number of incorrect messages it returns, even
if this behavior allows some issues to go undetected.
Sometimes, it produces messages that do not apply to your situation.
When provided with message, click the Detail button for additional information, which can help
you to make this determination. Error messages are almost always problems.
However, many warnings are suggestions to look at something in the code that is unusual and
therefore suspect, but might be correct in your case.
Suppress a warning message if you are certain that the message does not apply to your situation.
If your reason for suppressing a message is subtle or obscure, include a comment giving the
rationale. That way, those who read your code are aware of the situation.
For details, see Adjust Code Analyzer Message Indicators and Messages.
These sections describe code analysis limitations with respect to the following:
Distinguish Function Names from Variable Names
Distinguish Structures from Handle Objects
Distinguish Built-In Functions from Overloaded Functions
Determine the Size or Shape of Variables
Analyze Class Definitions with Superclasses
Analyze Class Methods
Distinguish Function Names from Variable Names
Code analysis cannot always distinguish function names from variable names. For the following
code, if the Code Analyzer message is enabled, code analysis returns the message, Code
Analyzer cannot determine whether xyz is a variable or a
function, and assumes it is a function. Code analysis cannot make a
determination because xyz has no obvious value assigned to it. However, the program might
have placed the value in the workspace in a way that code analysis cannot detect.
function y=foo(x)
.
.
.
y = xyz(x);
end
For example, in the following code, xyz can be a function, or can be a variable loaded from the
MAT-file. Code analysis has no way of making a determination.
function y=foo(x)
load abc.mat
y = xyz(x);
end
Variables might also be undetected by code analysis when you use the eval, evalc, evalin,
or assignin functions.
If code analysis mistakes a variable for a function, do one of the following:
Initialize the variable so that code analysis does not treat it as a function.
For the load function, specify the variable name explicitly in the load command line. For
example:
function y=foo(x)
load abc.mat xyz
y = xyz(x);
end
Distinguish Structures from Handle Objects
Code analysis cannot always distinguish structures from handle objects. In the following code, if
x is a structure, you might expect a Code Analyzer message indicating that the code never uses
the updated value of the structure. If x is a handle object, however, then this code can be correct.
function foo(x)
x.a = 3;
end
Code analysis cannot determine whether x is a structure or a handle object. To minimize the
number of incorrect messages, code analysis returns no message for the previous code, even
though it might contain a subtle and serious bug.
Distinguish Built-In Functions from Overloaded Functions
Code analysis does not use the MATLAB path information because it can be different,
depending on whether you are editing or running the program. If some built-in functions are
overloaded in a class or on the path, Code Analyzer messages might apply to the built-in
function, but not to the overloaded function you are calling. In this case, suppress the message on
the line where it appears or suppress it for the entire file.
For information on suppressing messages, see Adjust Code Analyzer Message Indicators and
Messages.
Determine the Size or Shape of Variables
Code analysis has a limited ability to determine the type of variables and the shape of matrixes.
Code analysis might produce messages that are appropriate for the most common case, such as
for vectors. However, these messages might be inappropriate for less common cases, such as for
matrixes.
class you are defining, then it cannot provide these checks.
Enable MATLAB Compiler Deployment Messages
You can switch between showing or hiding Compiler deployment messages when you work on a
file. Change the Code Analyzer preference for this message category. Your choice likely
depends on whether you are working on a file to be deployed. When you change the preference,
it also changes the setting in the Editor. The converse is also true—when you change the setting
from the Editor, it effectively changes this preference. However, if the dialog box is open at the
time you modify the setting in the Editor, you will not see the changes reflected in the
Preferences dialog box . Whether you change the setting from the Editor or from the Preferences
dialog box, it applies to the Editor and to the Code Analyzer Report.
To enable MATLAB Compiler™ deployment messages:
On the Home tab, in the Environment section, click
Preferences.
The Preferences dialog box opens.
Select Code Analyzer.
Clear individual messages that you do not want to display for your code (if any).
Decide if you want to save these settings, so you can reuse them next time you work on a file to
be deployed.
The settings txt file, which you can create as described in Save and Reuse Code Analyzer
Message Settings, includes the status of this setting.
Unit – V
Simulink
Introduction:
Simulink (Simulation and Link) is an extension of MATLAB by Mathworks Inc. It works with
MATLAB to offer modeling, simulating, and analyzing of dynamical systems under a graphical user
interface (GUI) environment. The construction of a model is simplified with click-and-drag mouse
operations. Simulink includes a comprehensive block library of toolboxes for both linear and nonlinear
analyses.
Models are hierarchical, which allow using both top-down and bottom-up approaches. As Simulink is an
integral part of MATLAB, it is easy to switch back and forth during the analysis process and thus, the
user may take full advantage of features offered in both environments. This tutorial presents the basic
features of Simulink and is focused on control systems as it has been written for students in
my control systems course.
Getting Started
To start Double click Matlab program on your desktop.
From Matlab command window, enter:
>> simulink
Simulink's library browser window like one shown below will pop up presenting the block set for model
construction.
To see the content of the blockset, click on the "+" sign at the beginning of each
toolbox.
To start a model click on the NEW FILE ICON as shown in the screenshot above.
A new window will appear on the screen. You will be constructing your model in this window. Also in
this window the constructed model is simulated. A screenshot of a typical working (model) window that
looks like one shown below:
The best way to understand simulink more extensively is to familiarize yourself with the structure and the
environment that is consisted in Simulink. Take a look through the various toolboxes to see all that
Simulink can offer. You may not understand what each and every object does, but with more experience
with the program you will become more familiar with the various tools.
The best way to learn is to do it on your own and make mistakes, believe me even the person writing this
tutorial made more then his share of mistakes in order to learn what the right move were.
The purpose of this tutorial is to analyze a simple spring-damper system, which resembles a One degree
of freedom model of a vehicle traveling over a rough road surface shown in Figure 1 below:
The various given information that is useful for this example are:
Vehicle mass ( m ):
1200 kg
Spring constant ( k ):
400 kN/m
Damping constant ( c ): 20x10^3 kg/s
Velocity of vehicle ( v ):
100 km /hr
Amplitude ( Y ):
0.05 m
wavelength ( λ ):
6m
Note that the problem can be modeled as a base vibration problem as shown in the model in Figure 1,
where the frequency of the base excitation is a function of the vehicle speed and road roughness:
Another way to look at this problem is in differential form which is stated as the following:
To begin this example we must first consider the input of the model. We are going to consider a simple
sine wave for the rough road surface with the parameters of wavelength and amplitude as stated above.
We can now move to the system by following these steps:
STEP 1: CREATING BLOCKS.
From BLOCK SET CATEGORIES section of the SIMULINK LIBRARY BROWSER
window, click on the "+" sign next to the Simulink group to expand the tree and
select (click on) Sources:
A set of blocks will appear in the BLOCKSET group. Click on the Sine Wave block and drag it to the
workspace window (also known as model window). Now you have established a source of your model.
Introduction: Simulink Modeling
In Simulink, it is very straightforward to represent and then simulate a mathematical model
representing a physical system. Models are represented graphically in Simulink as block
diagrams. A wide array of blocks are available to the user in provided libraries for representing
various phenomena and models in a range of formats. One of the primary advantages of
employing Simulink (and simulation in general) for the analysis of dynamic systems is that it
allows us to quickly analyze the response of complicated systems that may be prohibitively
difficult to analyze analytically. Simulink is able to numerically approximate the solutions to
mathematical models that we are unable to, or don't wish to, solve "by hand."
In general, the mathematical equations representing a given system that serve as the basis for a
Simulink model can be derived from physical laws. In this page we will demonstrate how to
derive a mathematical model and then implement that model in Simulink. This model is then
employed in the Introduction: Simulink Control page in order to demonstrate how to employ
Simulink to design and simulate the control for a system.
Train system
In this example, we will consider a toy train consisting of an engine and a car. Assuming that the
train only travels in one dimension (along the track), we want to apply control to the train so that
it starts and comes to rest smoothly, and so that it can track a constant speed command with
minimal error in steady state.
The mass of the engine and the car will be represented by
and
, respectively. Furthermore,
the engine and car are connected via a coupling with stiffness . In other words, the coupling is
modeled as a spring with a spring constant . The force represents the force generated between
the wheels of the engine and the track, while represents the coefficient of rolling friction.
Constructing the Simulink model
This set of system equations can now be represented graphically without further manipulation.
Specifically, we will construct two copies (one for each mass) of the general expression
or
. First, open Simulink and open a new model window. Then drag two
Sum blocks (from the Math Operations library) into your model window and place them
approximately as shown in the figure below.
The outputs of each of these Sum blocks represents the sum of the forces acting on each mass.
Multiplying each output signal by
will give us the corresponding acceleration of each mass.
Now drag two Gain blocks (from the Math Operations Library) into your model and attach each
one with a line from the output of one of the Sum blocks. Label these two signals as "Sum_F1"
and "Sum_F2" in order to make your model more clear. This is accomplished by double-clicking
in the space above each of the two signal lines and entering the desired label.
These Gain blocks should contain
for each of the masses. We will define the variables M1
and M2 in the MATLAB workspace, so we can just enter the corresponding variable names in
each of the Gain blocks. Double-click on the upper Gain block and enter "1/M1" into the Gain
field. Similarly, enter "1/M2" in the Gain field of the second Gain block.
You will notice that the gains did not appear in the image of the Gain blocks, rather the blocks
display a value of -K-. This is because the blocks are too small on the screen to show the full
variable name inside the triangle. The blocks can be resized so that the actual gain value can be
seen. To resize a block, select it by clicking on it once. Small squares will appear at the corners.
Drag one of these squares to stretch the block. Your model should appear as below.
The outputs of these gain blocks are the accelerations of each of the masses (the train engine and
car). The governing equations we derived above depend on the velocities and displacements of
the masses. Since velocity can be determined by integrating acceleration, and position can be
determined by integrating velocity, we can generate these signals employing integrator blocks.
Drag a total of four Integrator blocks from the Continuous library into your model, two for each
of our two accelerations. Connect these blocks and label the signals as shown below.
Specifically, the first inegrator takes the acceleration of mass 1 ("x1_ddot") as an input and
generates the velocity of mass 1 ("x1_dot"). The second integrator then takes this velocity and
outputs the displacement of the first mass ("x1"). The same pattern holds for the integrators for
the second mass.
Now, drag two Scopes from the Sinks library into your model and connect them to the outputs of
these integrators. Label them "x1" and "x2".
Now we are ready to add the forces acting on each mass. First, we need to adjust the inputs on
each Sum block to represent the proper number of forces (we will worry about the signs later).
Since there is a total of three forces acting on mass 1, double-click on the corresponding Sum
block and change the List of signs field to "|+++". The symbol "|" serves as a spacer. There are
only 2 forces acting on mass 2, therefore, we can leave that Sum block alone for now.
The first force acting on mass 1 is just the input force, . Drag a Signal Generator block from
the Sources library and connect it to the uppermost input of the corresponding Sum block. Label
this signal as "F".
The next force acting on mass 1 is the rolling resistance force. Recall that this force is modeled
as follows.
(3)
To generate this force, we can tap off the velocity signal and multiply by an appropriate gain.
Drag a Gain block into your model window. Tap off the "x1_dot" signal and connect it to the
input of this new Gain block (draw this line in several steps if necessary). Connect the output of
the Gain block to the second input of the Sum block. Double-click the Gain block and enter
"mu*g*M1" into the Gain field. The rolling resistance force, however, acts in the negative
direction. Therefore, change the list of signs of the Sum block to "|+-+". Next, resize the Gain
block to display the full gain and label the output of the Gain block "Frr1". Your model should
now appear as follows.
The last force acting on mass 1 is the spring force. Recall that this force is equal to the following.
(4)
Therefore, we need to generate a signal
which we can then be multiplied by a gain to
create the force. Drag a Subtraction block (or a Sum block or an Addition block) below the rest
of your model. In order to change the direction of this block, right-click on the block and choose
Format > Flip block from the resulting menu. Alternatively, you can select the block then hit
Ctrl-I. Now, tap off the "x2" signal and connect it to the negative input of the Subtract block.
Also, tap off the "x1" signal and connect it to the positive input. This will cause signal lines to
cross. Lines may cross, but they are only actually connected where a small block appears (such
as at a tap point).
Now, we can multiply this difference by the spring constant to generate the spring force. Drag a
Gain block into your model to the left of the Subtraction block. Change the value of the Gain
block to "k" and connect the output of the Subtract block to its input. Then connect the output of
the Gain block to the third input of the Sum block for mass 1 and label the signal "Fs". Since the
spring force acts on mass 1 in the negative direction, it is necessary to again change the list of
signs of the Sum block to "|+--". Your model should appear as follows.
We can now apply forces to mass 2. For the first force, we will use the same spring force we just
generated, except that it is applied to mass 2 in the positive direction. Simply tap off the spring
force signal "Fs" and connect it to the first input of the Sum block for mass 2.
The last force applied to mass 2 is its rolling resistance force. This force is generated in an
analogous manner to the rolling resistance force applied to mass 1. Tap off the signal "x2_dot"
and multiply it by a Gain block with value "mu*g*M2". Then connect the output of the Gain
block to the second input of the corresponding Sum block and label the signal "Frr2". Changing
the second input of the Sum block to be negative will lead to the following model.
Now the model is complete. We simply need to supply the proper input and define the output of
interest. The input to the system is the force generated by the engine. Within the Simulink
model, we have already defined the force to be the output of a Signal Generator block. The
output of the system, which we will observe and ultimately try to control, will be the velocity of
the train engine. Add another Scope block to your model from the Sinks library. Tap a line from
the "x1_dot" signal and connect it to the Scope block. Label this scope as "x1_dot" and your
model should appear as in the following.
Now, the model is complete and should be saved. You can also download the completed model
here.
Running the model
Before running the model, we need to assign numerical values to each of the variables used in
the model. For the train system, we will employ the following values.
= 1 kg
= 0.5 kg
= 1 N/sec
=1N
= 0.02 sec/m
= 9.8 m/s^2
Create a new m-file and enter the following commands.
M1
M2
k
F
mu
g
=
=
=
=
=
=
1;
0.5;
1;
1;
0.02;
9.8;Execute
your m-file in the MATLAB command window to define these values.
Simulink will recognize these MATLAB variables for use in the model. Now, we need to give an
appropriate input to the engine. Double-click on he Signal Generator block (outputs "F"). Select
square from the Wave form drop-down menu and set the Frequency field to equal "0.001".
You may leave the Units as the default Hertz. Also enter "-1" into the Amplitude field (positive
amplitude steps negative before stepping positive).
The last step before running the simulation is to select an appropriate simulation time. To view
one cycle of the 0.001 Hz square wave, we should simulate the model for 1000 seconds. Select
Parameters from the Simulation menu at the top of the model window and change the Stop
Time field to "1000". Close the dialog box.
Now, run the simulation and open the "x1_dot" scope to examine the velocity output (hit
autoscale). The input was a square wave with two steps, one positive and one negative.
Physically, this means that the engine first went forward, then backward. The velocity output
reflects this.
In this page we derived the mathematical model for the train system from first principles and
then represented the derived equations within Simulink. An alternative option that is now
available is to represent a dynamic system employing the physical modeling tool Simscape.
Simscape is an addition to Simulink that allows a user to model a system employing blocks that
represent physical quantities (and objects) such as inertias and joints, or resistances and
inductors. Employing Simscape allows the user to simulate a physical system without deriving
the governing mathematical equations.
Continuing on to the Introduction: Simulink Control page, we will employ the model derived in
this page to demonstrate how to use Simulink to design the control for our train system.
In control engineering, a state space representation is a mathematical model of a physical
system as a set of input, output and state variables related by first-order differential equations. To
abstract from the number of inputs, outputs and states, the variables are expressed as vectors.
Additionally, if the dynamical system is linear and time invariant, the differential and algebraic
equations may be written in matrix form. The state space representation (also known as the
"time-domain approach") provides a convenient and compact way to model and analyze systems
with multiple inputs and outputs. With inputs and outputs, we would otherwise have to write
down
Laplace transforms to encode all the information about a system. Unlike the
frequency domain approach, the use of the state space representation is not limited to systems
with linear components and zero initial conditions. "State space" refers to the space whose axes
are the state variables. The state of the system can be represented as a vector within that space.
State variables
Block diagram representation of the state space equations
The internal state variables are the smallest possible subset of system variables that can represent
the entire state of the system at any given time. The minimum number of state variables required
to represent a given system, , is usually equal to the order of the system's defining differential
equation. If the system is represented in transfer function form, the minimum number of state
variables is equal to the order of the transfer function's denominator after it has been reduced to a
proper fraction. It is important to understand that converting a state space realization to a transfer
function form may lose some internal information about the system, and may provide a
description of a system which is stable, when the state-space realization is unstable at certain
points. In electric circuits, the number of state variables is often, though not always, the same as
the number of energy storage elements in the circuit such as capacitors and inductors. The state
variables defined must be linearly independent; no state variable can be written as a linear
combination of the other state variables or the system will not be able to be solved.[citation needed]
Linear systems
The most general state-space representation of a linear system with
state variables is written in the following form:
inputs,
outputs and
where:
is called the "state vector",
;
is called the "output vector",
;
is called the "input (or control) vector",
;
is the "state (or system) matrix",
is the "input matrix",
,
,
is the "output matrix",
,
is the "feedthrough (or feedforward) matrix" (in cases where the system model does not
have a direct feedthrough,
is the zero matrix),
,
.
In this general formulation, all matrices are allowed to be time-variant (i.e. their elements can
depend on time); however, in the common LTI case, matrices will be time invariant. The time
variable can be continuous (e.g.
) or discrete (e.g.
). In the latter case, the time
variable is usually used instead of . Hybrid systems allow for time domains that have both
continuous and discrete parts. Depending on the assumptions taken, the state-space model
representation can assume the following forms:
System type
State-space model
Continuous time-invariant
Continuous time-variant
Explicit discrete time-invariant
Explicit discrete time-variant
Laplace domain of
continuous time-invariant
Z-domain of
discrete time-invariant
Example: Continuous-time LTI case
Stability and natural response characteristics of a continuous-time LTI system (i.e., linear with
matrices that are constant with respect to time) can be studied from the eigenvalues of the matrix
A. The stability of a time-invariant state-space model can be determined by looking at the
system's transfer function in factored form. It will then look something like this:
The denominator of the transfer function is equal to the characteristic polynomial found by
taking the determinant of
,
The roots of this polynomial (the eigenvalues) are the system transfer function's poles (i.e., the
singularities where the transfer function's magnitude is unbounded). These poles can be used to
analyze whether the system is asymptotically stable or marginally stable. An alternative
approach to determining stability, which does not involve calculating eigenvalues, is to analyze
the system's Lyapunov stability.
The zeros found in the numerator of
system is minimum phase.
can similarly be used to determine whether the
The system may still be input–output stable (see BIBO stable) even though it is not internally
stable. This may be the case if unstable poles are canceled out by zeros (i.e., if those singularities
in the transfer function are removable).
Controllability
Main article: Controllability
Thus, state controllability condition implies that it is possible – by admissible inputs – to steer
the states from any initial value to any final value within some finite time window. A continuous
time-invariant linear state-space model is controllable if and only if
Where rank is the number of linearly independent rows in a matrix.
Observability
Main article: Observability
Observability is a measure for how well internal states of a system can be inferred by knowledge
of its external outputs. The observability and controllability of a system are mathematical duals
(i.e., as controllability provides that an input is available that brings any initial state to any
desired final state, observability provides that knowing an output trajectory provides enough
information to predict the initial state of the system).
A continuous time-invariant linear state-space model is observable if and only if
Transfer function
The "transfer function" of a continuous time-invariant linear state-space model can be derived in
the following way:
First, taking the Laplace transform of
yields
Next, we simplify for
, giving
and thus
Substituting for
in the output equation
giving
Because the transfer function
we take
is defined as the ratio of the output to the input of a system,
and substitute the previous expression for
with respect to
, giving
Clearly
must have by dimensionality, and thus has a total of
elements. So for every
input there are transfer functions with one for each output. This is why the state-space
representation can easily be the preferred choice for multiple-input, multiple-output (MIMO)
systems.
Canonical realizations
Main article: Realization (systems)
Any given transfer function which is strictly proper can easily be transferred into state-space by
the following approach (this example is for a 4-dimensional, single-input, single-output system):
Given a transfer function, expand it to reveal all coefficients in both the numerator and
denominator. This should result in the following form:
The coefficients can now be inserted directly into the state-space model by the following
approach:
This state-space realization is called controllable canonical form because the resulting model is
guaranteed to be controllable (i.e., because the control enters a chain of integrators, it has the
ability to move every state).
The transfer function coefficients can also be used to construct another type of canonical form
This state-space realization is called observable canonical form because the resulting model is
guaranteed to be observable (i.e., because the output exists from a chain of integrators, every
state has an effect on the output).
Proper transfer functions
Transfer functions which are only proper (and not strictly proper) can also be realised quite
easily. The trick here is to separate the transfer function into two parts: a strictly proper part and
a constant.
The strictly proper transfer function can then be transformed into a canonical state space
realization using techniques shown above. The state space realization of the constant is trivially
. Together we then get a state space realization with matrices A,B and C
determined by the strictly proper part, and matrix D determined by the constant.
Here is an example to clear things up a bit:
which yields the following controllable realization
Notice how the output also depends directly on the input. This is due to the
the transfer function.
constant in
Feedback
Typical state space model with feedback
A common method for feedback is to multiply the output by a matrix K and setting this as the
input to the system:
. Since the values of K are unrestricted the values can
easily be negated for negative feedback. The presence of a negative sign (the common notation)
is merely a notational one and its absence has no impact on the end results.
becomes
solving the output equation for
and substituting in the state equation results in
The advantage of this is that the eigenvalues of A can be controlled by setting K appropriately
through eigendecomposition of
. This assumes that the closedloop system is controllable or that the unstable eigenvalues of A can be made stable through
appropriate choice of K.
Example
For a strictly proper system D equals zero. Another fairly common situation is when all states are
outputs, i.e. y = x, which yields C = I, the Identity matrix. This would then result in the simpler
equations
This reduces the necessary eigendecomposition to just
Feedback with setpoint (reference) input
.
Output feedback with set point
In addition to feedback, an input,
, can be added such that
.
becomes
solving the output equation for
and substituting in the state equation results in
One fairly common simplification to this system is removing D, which reduces the equations to
Moving object example
A classical linear system is that of one-dimensional movement of an object. The Newton's laws
of motion for an object moving horizontally on a plane and attached to a wall with a spring
where
is position;
is velocity;
is acceleration
is an applied force
is the viscous friction coefficient
is the spring constant
is the mass of the object
The state equation would then become
where
represents the position of the object
is the velocity of the object
is the acceleration of the object
the output
is the position of the object
The controllability test is then
which has full rank for all
and
.
The observability test is then
which also has full rank. Therefore, this system is both controllable and observable.
Nonlinear systems
The more general form of a state space model can be written as two functions.
The first is the state equation and the latter is the output equation. If the function
is a
linear combination of states and inputs then the equations can be written in matrix notation like
above. The
no inputs).
argument to the functions can be dropped if the system is unforced (i.e., it has
Pendulum example
A classic nonlinear system is a simple unforced pendulum
where
is the angle of the pendulum with respect to the direction of gravity
is the mass of the pendulum (pendulum rod's mass is assumed to be zero)
is the gravitational acceleration
is coefficient of friction at the pivot point
is the radius of the pendulum (to the center of gravity of the mass
)
The state equations are then
where
is the angle of the pendulum
is the rotational velocity of the pendulum
is the rotational acceleration of the pendulum
Instead, the state equation can be written in the general form
The equilibrium/stationary points of a system are when
pendulum are those that satisfy
and so the equilibrium points of a
Using Simulink
Masking a Subsystem
To mask a subsystem,
1. Select the subsystem.
2. Select Edit mask from the Edit menu of the model window or from the block's context
menu. (Right-click the subsystem block to display its context menu.)
1. The Mask Editor appears.
See The Mask Editor for a detailed description of the Mask Editor.
3. Use the Mask Editor's tabbed panes to perform any of the following tasks.
o Create a custom icon for the masked subsytem (see The Icon Pane)
o Create parameters that allow a user to set subsystem options (see The Mask
Editor)
o Initialize the masked subsystem's parameters
o Create online user documentation for the subsystem
4. Click Apply to apply the mask to the subsystem or OK to apply the mask and dismiss the
Mask Editor.
© Copyright 2026 Paperzz