KEMBAR78
MSES Note | PDF | Matlab | Matrix (Mathematics)
0% found this document useful (0 votes)
108 views79 pages

MSES Note

This document provides an overview of MATLAB, including what it is, where it is used, why it is useful for engineers, and how to start and quit a MATLAB session. Specifically: - MATLAB is a numerical computing environment and programming language. It was originally designed for matrix manipulation but is now used more broadly for computation, visualization, and programming. - Typical uses of MATLAB include math and computation, algorithm development, modeling and simulation, data analysis and visualization, and engineering applications. - MATLAB is useful for engineers as it is widely used in engineering education and industry. It features toolboxes for specialized domains like signal processing and control systems. - To start MATLAB, double click the desktop icon. The

Uploaded by

Abdul Sattar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
108 views79 pages

MSES Note

This document provides an overview of MATLAB, including what it is, where it is used, why it is useful for engineers, and how to start and quit a MATLAB session. Specifically: - MATLAB is a numerical computing environment and programming language. It was originally designed for matrix manipulation but is now used more broadly for computation, visualization, and programming. - Typical uses of MATLAB include math and computation, algorithm development, modeling and simulation, data analysis and visualization, and engineering applications. - MATLAB is useful for engineers as it is widely used in engineering education and industry. It features toolboxes for specialized domains like signal processing and control systems. - To start MATLAB, double click the desktop icon. The

Uploaded by

Abdul Sattar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 79

UNIT - 1

Micro Syllabus:
MATLAB, MATLAB System, Starting MATLAB, Quitting MATLAB, Inputting and outputting
methods, File Types, Variables and its Assignment.

1.1 What is MATLAB?


 The name MATLAB stands for MATrix LABoratory.
 A numerical analyst called Cleve Moler wrote the first version of MATLAB in the 1970.
 MATLAB is a high-performance language for technical computing. It integrates
computation, visualization, and programming in an easy-to-use environment where
problems and solutions are expressed in familiar mathematical notation.

1.2 Where (Typical uses) MATLAB?


 Math and computation.
 Algorithm development.
 Modelling, simulation, and prototyping.
 Data analysis, exploration, and visualization.
 Scientific and engineering graphics.
 Application development, including graphical user interface building.

1.3 Why MATLAB for Engineers?


 In university environments, it is the standard instructional tool for introductory and
advanced courses in mathematics, engineering and science.
 In industry, MATLAB is the tool of choice for high productivity research, development
and analysis.
 MATLAB features a family of application-specific solutions called toolboxes, toolboxes
allow you to learn and apply specialized technology.
 Areas in which toolboxes are available include signal processing, control systems, neural
networks, fuzzy logic, wavelets and many others.
 Moreover one can use MATLAB as a Advanced Scientific calculator.

1.4 Introduction

The name MATLAB stands for MATrix LABoratory. MATLAB was written originally to
provide easy access to matrix software developed by the LINPACK (linear system package) and
EISPACK (Eigen system package) projects.

MATLAB is a high-performance language for technical computing. It integrates


computation, visualization, and programming environment. Furthermore, MATLAB is a modern
programming language environment: it has sophisticated data structures, contains built-in editing
and debugging tools, and supports object-oriented programming. These factors make MATLAB
an excellent tool for teaching and research.

1
MATLAB has many advantages compared to conventional computer languages (e.g., C,
FORTRAN) for solving technical problems. MATLAB is an interactive system whose basic data
element is an array that does not require dimensioning. The software package has been
commercially available since 1984 and is now considered as a standard tool at most universities
and industries worldwide.

It has powerful built-in routines that enable a very wide variety of computations. It also has
easy to use graphics commands that make the visualization of results immediately available.
Specific applications are collected in packages referred to as toolbox. There are toolboxes for
signal processing, symbolic computation, control theory, simulation, optimization, and several
other fields of applied science and engineering.

1.5 The MATLAB System:


It consists of:
 Development Environment.
 The MATLAB Mathematical Function Library.
 The MATLAB Language.
 Graphic Handler.
 The MATLAB Application Program Interface(API).

Among the above, the Development Environment is the one engineers should concentrate on.
Therefore, Development Environment is mostly emphasised with
 Working with programming (Script’s and Function’s).
 Working with Simulink (Block Sets).
 Working with GUI(objects).

1.6 A minimum MATLAB session


The goal of this minimum session (also called starting and exiting sessions) is to learn the first
steps:
• How to logon
• Invoke MATLAB
• Do a few simple calculations
• How to quit MATLAB

1.7 Starting an d Q ui tt i n g MATLAB


After logging into your account, you can enter MATLAB by double-clicking on the MATLAB
shortcut icon (MATLAB 7.0.4) on your Windows desktop.
When you start MATLAB, a special window called the MATLAB desktop appears. The desktop
is a window that contains other windows.
To end your MATLAB session, type quit in the Command Window, or select File−→Exit
MATLAB in the desktop main menu.

2
1.8 The major work stations:
The major work stations within or accessible from the desktop are:
1. Direct windows:
• The Command Window
• The Command History
• The Workspace
• The Current Directory

2. Indirect windows:
• Editor
• Simulink
• Figure window
• The Help Browser

When MATLAB is started for the first time, the screen looks like the one that shown in the
Figure 1.1. This illustration also shows the default configuration of the MATLAB
desktop.Youcancustomizethearrangementoftoolsanddocumentstosuityourneeds.

Now, we are interested in doing some simple calculations. We will assume that you have
sufficient understanding of your computer under which MATLAB is being run.
You are now faced with the MATLAB desktop on your computer, which contains the prompt
(>>)intheCommandWindow.Usually,thereare2typesofprompt:

>> for fullversion


EDU> for educational version

Note: To simplify the notation, we will use this prompt, >>, as a standard prompt sign, though
our MATLAB version is for educational purpose.

1.9 The MATLAB File Types:


The MATLAB File Types or Environment Extensions:
 path --path to directory
 m -- cell array of m-file names.
 mat -- cell array of mat-file names.
 mex -- cell array of mex-file names.
 mdl -- cell array of mdl-file names.
 p -- cell array of p-file names.
 classes -- cell array of class directory names.
 packages -- cell array of package directory names.
 Fig -- path to figure window
3
1.10 Saving output to a file
In addition to displaying output on the screen, the command fprintf can be used for writing the
output to a file. The saved data can subsequently be used by MATLAB or other softwares.

To save the results of some computation to a file in a text format requires the following
steps:
1. Open a file using fopen
2. Write the output using fprintf
3. Close the file using fclose

UNIT-II
Micro Syllabus: Scripts, Making Variables, Manipulating Variables, Basic Plotting, Indexing,
Examples

The Command Window


This is the one of the important direct window where one can do inputting, compiling
and executing and outputting.
 In command window we see “>>” which is called as command prompt.
 By default cursor (Blinking line) is placed next to the command prompt(>>|).This is
the place where we have to type our commands.
 A given command is executed if we press Enter key.
 The data once executed in command window can’t be modified. It has to be recalled
once again( use or keys), modified and should be re-executed.
 If a “;” is typed at the end of command the output of the command is not displayed, but
command is said to be executed if once Enter key is pressed.
 The clc command clears the command window. Once it is typed a clear command
window is displayed.
 If a “%” is typed in the beginning of a line, the line is designated as a comment. This
means that the comment is not executed if press Enter key.
Managing the workspace
The contents of the workspace persist between the executions of separate commands. There-
fore, it is possible for the results of one problem to have an effect on the next one. To avoid this
possibility, it is a good idea to issue a clear command at the start of each new inde- pendent
calculation.
>> clear
The command clear or clear all removes all variables from the workspace. This frees up
system memory. In order to display a list of the variables currently in the memory, type
>> who
while, whos will give more details which include size, space allocation, and class of the
variables.

4
Keeping track of your work session
It is possible to keep track of everything done during a MATLAB session with the diary
command.
>> diary
or give a name to a created file,
>> diary FileName
where FileName could be any arbitrary name you choose.
The function diary is useful if you want to save a complete MATLAB session. They save
all input and output as they appear in the MATLAB window. When you want to stop the
recording, enter diary off. If you want to start recording again, enter diary on. The file that is
created is a simple text file. It can be opened by an editor or a word processing program and
edited to remove extraneous material, or to add your comments. You can use the function type to
view the diary file or you can edit in a text editor or print. This command is useful, for example
in the process of preparing a homework or lab submission.
>>help general - General purpose commands.
>>help ops - Operators and special characters.
>>help lang- Programming language constants.
>>help elmat- Elementary matrices.
>>help elfun- Elementary math functions.
>>help specfun- Specialized math functions.
Miscellaneous commands
Here are few additional useful commands:
• To clear the Command Window, type clc
• To abort a MATLAB computation, type ctrl-c
• To continue a line, type . . .
Getting help
To view the online documentation, select MATLAB Help from Help menu or MATLAB Help
directly in the Command Window. The preferred method is to use the Help Browser. The Help
Browser can be started by selecting the ? icon from the desktop toolbar. On the other hand,
information about any command is available by typing
>> help Command
Another way to get help is to use the lookfor command. The lookfor command differs from the
help command. The help command searches for an exact function name match, while the lookfor
command searches the quick summary information in each function for a match. For example,
suppose that we were looking for a function to take the inverse of a matrix. Since MATLAB
does not have a function named inverse, the command help inverse will produce nothing. On the
other hand, the command lookfor inverse will produce detailed information, which includes the
function of interest, inv.
>>lookfor inverse
Note - At this particular time of our study, it is important to emphasize one main point. Because
MATLAB is a huge program; it is impossible to cover all the details of each function one by
one. However, we will give you information how to get help. Here are some examples:
• Use on-line help to request info on a specific function

5
>> help sqrt
• In the current version (MATLAB version 7), the doc function opens the on-line version of
the help manual. This is very helpful for more complex commands.
>> doc plot
• Use lookfor to find functions by keywords. The general form is
>>lookforFunctionName
2.1 Using MATLAB as a calculator
As an example of a simple interactive calculation, just type the expression you want to
evaluate.Let’sstartattheverybeginning.Forexample,let’ssupposeyouwanttocalculate
the expression, 1 + 2 × 3. You type it at the prompt command (>>) as follows,
>> 1+2*3
ans =7
You will have noticed that if you do not specify an output variable, MATLAB uses a default
variable ans, short for answer, to store the results of the current calculation. Note that the
variable ans is created (or overwritten, if it is already existed). To avoid this, you may assign a
value to a variable or output argument name. For example,
>>x=1+2*3
x =7
will result in x being given the value 1 + 2 × 3 = 7. This variable name can always
beusedtorefertotheresultsofthepreviouscomputations.Therefore,computing4xwill resultin
>>4*x
ans =28.0000
Beforeweconcludethisminimumsession,Table2.1givesthepartiallistofarithmetic operators.

Symbol Operation Example

Addition 2 +3
− Subtraction 2−3
* Multiplication 2∗3
/ Division 2/3

2.1.1 Operator precedence


We can build expressions that use any combination of arithmetic, relational, and logical
operators. Precedence rules determine the order in which MATLAB evaluates an expression. We
have already seen this in the “Tutorial Lessons”.
Here we add other operators in the list. The precedence rules for MATLAB are shown in
this list (Table 2.2), ordered from highest (1) to lowest (9) precedence level. Operators are
evaluated from left to right.

Table 2.2: Operator precedence

6
Precedence Operator

1 Parentheses ()
2 Transpose (. t), power (.ˆ), matrix power (ˆ)
3 Unary plus (+), unary minus (−), logical negation (∼)
4 Multiplication (. ∗), right division (. /), left division (.\),
matrix multiplication (∗), matrix right division (/),
matrix left division (\)
5 Addition (+), subtraction (−)
6 Colon operator (:)
7 Less than (<), less than or equal to (≤), greater (>),
greater than or equal to (≥), equal to (==), not equal to (∼=)
8 Element-wise AND, (&)
9 Element-wise OR, (|)

write some variable length strings to a


fileop =fopen(’weekdays.txt’,’wt’);
fprintf(op,’Sunday\nMonday\nTuesday\nWednesday\n’);
fprintf(op,’Thursday\nFriday\nSaturday\n’);
fclose(op);

This file (weekdays.txt) can be opened with any program that can read .txtfile.

2.2 Variables:
MATLAB variables are created when they appear on the left of an equal sign. The generic
statement
>>variable = expression

creates the ``variable'' and assigns to it the value of the expression on the right
hand side. You do not need to define or declare a variable before it is used.
• By default the results are stored with variable ans.
• We can use any user defined names to store numbers.
• Legal names consist of any combination of letters and digits, starting with
a letter.
• We should avoid usage of some pre specified names like eps, pi, i, j.

2.2.1 Creating MATLAB variables


MATLAB variables are created with an assignment statement. The syntax of variable assignment
is
variable name = a value (or an expression)
For example,
>> x = expression
where expression is a combination of numerical values, mathematical operators, variables, and
function calls. On other words, expression can involve:
• manual entry.

7
• built-in functions.
• user-defined functions.
2.2.2 Overwriting variable
Once a variable has been created, it can be reassigned. In addition, if you do not wish to see the
intermediate results, you can suppress the numerical output by putting a semicolon (;) at the end
of the line. Then the sequence of commands looks like this:
>> t = 5;
>> t = t+1
t =6
2.2.3 Error messages
If we enter an expression incorrectly, MATLAB will return an error message. For example, in
the following, we left out the multiplication sign, *, in the following expression
>> x = 10;
>> 5x
??? 5x
Error: Unexpected MATLAB expression.
2.2.4 Making corrections
To make corrections, we can, of course retype the expressions. But if the expression islengthy,
we make more mistakes by typing a second time. A previously typed command can be recalled
with the up-arrow key ↑. When the command is displayed at the commandprompt, it can be
modified if needed and executed.
2.2.5 Controlling the hierarchy of operations or precedence
Let’s consider the previous arithmetic operation, but now we will include parentheses. For
example, 1 + 2 × 3 will become (1 + 2) × 3
>> (1+2)*3
ans 9
and, from previous example
>> 1+2*3
ans= 7
By adding parentheses, these two expressions give different results: 9 and 7.
The order in which MATLAB performs arithmetic operations is exactly that taught in high
school algebra courses. Exponentiations are done first, followed by multiplications and divisions,
and finally by additions and subtractions. However, the standard order of precedence of
arithmetic operations can be changed by inserting parentheses. For example,the result of 1+2×3
is quite different than the similar expression with parentheses (1+2)×3.The results are 7 and 9
respectively. Parentheses can always be used to overrule priority,and their use is recommended
in some complex expressions to avoid ambiguity.

Table 2.2: Hierarchy of arithmetic operations


Precedence Mathematical operations
First The contents of all parentheses are evaluated first, starting
from the innermost parentheses and working outward.
Second All exponentials are evaluated, working from left to right
Third All multiplications and divisions are evaluated, working
8
from left to right
Fourth All additions and subtractions are evaluated, starting
from left to right

Therefore, to make the evaluation of expressions unambiguous, MATLAB has estab-


lished a series of rules. The order in which the arithmetic operations are evaluated is given in
Table 2.2. MATLAB arithmetic operators obey the same precedence rules as those inmost
computer programs. For operators of equal precedence, evaluation is from left to right. Now,
consider another example:

In MATLAB, it becomes
>> 1/(2+3^2)+4/5*6/7
ans =
0.7766
or, if parentheses are missing,
>> 1/2+3^2+4/5*6/7
ans =
10.1857
So here what we get: two different results. Therefore, we want to emphasize the importance of
precedence rule in order to avoid ambiguity.

2.2.6 Controlling the appearance of floating point number


MATLAB by default displays only 4 decimals in the result of the calculations, for
example−163.6667, as shown in above examples. However, MATLAB does numerical
calculations in double precision, which is 15 digits. The command format controls how the
results ofcomputations are displayed. Here are some examples of the different formats together
with the resulting outputs.
>> format short
>> x=-163.6667
If we want to see all 15 digits, we use the command format long
>> format long
>> x= -1.636666666666667e+002
To return to the standard format, enter format short, or simply format.
There are several other formats. For more details, see the MATLAB documentation, or
type help format.
Note - Up to now, we have let MATLAB repeat everything that we enter at the prompt
(>>). Sometimes this is not quite useful, in particular when the output is pages en length. To
prevent MATLAB from echoing what we type, simply enter a semicolon (;) at the end of the
command. For example,
>> x=-163.6667;
and then ask about the value of x by typing,
>> x
X = -163.6667
2.2.7 Suppressing: Entering multiple statements
9
per line
It is possible to enter multiple statements per line. Use commas (,) or semicolons (;) to
enter more than one statement at once. Commas (,) allow multiple statements per line
without suppressing output.
>> a=7; b=cos(a), c=cosh(a)
b =
0.6570
c =
548.3170

2.3 Basic plotting


MATLAB has an excellent set of graphic tools. Plotting a given data set or the results
of computation is possible with very few commands. You are highly encouraged to plot
mathematical functions and results of analysis as often as possible. Trying to understand
mathematical equations with graphics is an enjoyable and very efficient way of learning math-
ematics. Being able to plot mathematical functions and data freely is the most important step,
and this section is written to assist you to do just that.

2.3.1 Creating simpleplots


The basic MATLAB graphing procedure, for example in 2D, is to take a vector of x- coordinates,
x = (x1, . . . ,xN), and a vector of y-coordinates, y = (y1, . . . , yN), locate the points (xi, yi), with i=
1, 2, . . . , n and then join them by straight lines. You need to prepare x and y in an identical array
form; namely, x and y are both row arrays or column arrays of the same length.
The MATLAB command to plot a graph is plot(x,y). The vectors x = (1, 2, 3, 4, 5, 6) and y
= (3, −1, 2, 4, 5, 1) produce the picture shown in Figure 2.1.
>> x = [1 2 3 4 5 6];
>> y = [3 -1 2 4 5 1];
>> plot(x,y)

Note: The plot functions has different forms depending on the input arguments. If y is a vector
plot(y)produces a piecewise linear graph of the elements of y versus the index of the elements of
y. If we specify two vectors, as mentioned above, plot(x,y) produces a graph of y versus x.
For example, to plot the function sin (x) on the interval [0, 2π], we first create a vector of x
values ranging from 0 to 2π, then compute the sine of these values, and finally plot the result:

10
Figure 2.1: Plot for the vectors x and y

Similarly to plot the sine wave

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

Notes:
• 0:pi/100:2*pi yields a vector that
– starts at0,
– takessteps(orincrements)ofπ/100,
– stopswhen2πisreached.
• Ifyouomittheincrement,MATLABautomaticallyincrementsby1.

2.4 Scripts

 A MATLAB script file (Called an M-file) is a text (plain ASCII) file that contains one or
more MATLAB commands and, optionally, comments.
 The file is saved with the extension ".m" and hence it is also called as M-Files.
 The place we write the scripts is called as Editor.
 When the filename (without the extension) is issued as a command in MATLAB, the file is
11
opened, read, and the commands are executed as if input from the keyboard. The result is
similar to running a program in C.
 The file name can be saved with a character, word, string and alphanumerics (but never
starting with a number).No spacing and special characters is to be used in saving a file.

2.4.1 Opening a Script file
The script file is to be opened if it is to be created. this can be done in two ways:
1. Go to file in task bar --> new --> script.
2. open script file directly in sub task bar.

2.4.2 Creating a Script file


To create an m-file, open the Matlab editor

1) It is not possible to execute more than one instruction in a command window and more over too
difficult to manipulate. so the best solution is to go to scripting in editor.

2) In editor all the written n lines are compiled, executed at a time and is outputted in a command
window at command line

A script can be filled with a sequence of Matlab commands that will be executed from top to
bottom just as if you had typed them on the command screen. These files have .m extensions
(automatically added in Windows) and can be executed by typing their names (without the .m
extension) in the command window. For example, if you create a script called test.m you can
execute it in the command window by typing test. Do not choose file names that start with
numbers, like 430lab1a.m. When Matlab receives the start of a number on the command line it
thinks a calculation is coming, and since 430lab1a is not a valid calculation Matlab will give you
an error.

2.4.3 Running script files


When you have a script written and saved, go to the window with the Matlab command prompt
and type the name of your file without the .m extension, like this: test Your script will then run. (Or
you can use the debug menu in the editor, or the “Save and Run” shortcut key, F5.)

2.5 Exercises :

Example 1 : plot the function f (x) = (sin(x)) ^ 2 + 2xcos(x) where x varying from -2π to 2π.

x = [-2*pi:0.1:2*pi]; y = sin(x) .^ 2 + 2 * x .* cos(x); plot(x,y)

12
Example 2 :Represent the graphs of the functions Sine(x), Sine(2x) and Sine(3x), varying in
the range (0,2pi) for x, all on the same axes.

The graphics, generated by the input is represented in:

>>fplot (@(x)[sin(x), sin(2*x), sin(3*x)], [0, 2 * pi])

Example 3: On the same axes represent the graphs of the functions y = sin (x2) and y = log
(sqrt (x)). The text of each equation is properly positioned within the graph.

We get the graph in Figure 4 considering the following MATLA B entry:

x = linspace (0,2,30);

y = sin(x.^2);

13
plot(x,y)

hold on

z = log(sqrt(x));

plot (x, z)

UNIT – III

Micro Syllabus:

Functions,Sub-Functions, Flow Control-IF Clauses, For loop, While Loop, Switch Statements and
Branching Statements, 2D Plotting- Line Plots, 3D Plotting-Image/Surface Plots, Vectorization.
in programming

3.1 Functions
 Matlab functions are of two types
1. Built in Functions/library functions.
2. User defined functions

3.1.1 Built in functions/ Library functions


MATLAB offers many predefined mathematical functions for technical computing which
contains a large set of mathematical functions.
Typing help elfun and help specfun calls up full lists of elementary and special functions
respectively.
There is a long list of mathematical functions that are built into MATLAB. These
functionsarecalledbuilt-ins.Manystandardmathematicalfunctions,suchassin(x),cos(x), tan(x), ex,
ln(x), are evaluated by the functions sin, cos, tan, exp, and log respectively in MATLAB.
Table 2.1 lists some commonly used functions, where variables x and y can be numbers,
vectors, or matrices.
Table 3.1: Elementary functions
14
cos(x) Cosine abs(x) Absolute value
sin(x) Sine sign(x) Signum function
tan(x) Tangent max(x) Maximum value
acos(x) Arc cosine min(x) Minimum value
asin(x) Arc sine ceil(x) Round towards +∞
atan(x) Arc tangent floor(x) Round towards −∞
exp(x) Exponential round(x) Round to nearest integer
sqrt(x) Square root rem(x) Remainder after division
log(x) Natural logarithm angle(x) Phase angle
log10(x) Common logarithm conj(x) Complex conjugate

In addition to the elementary functions, MATLAB includes a number of predefined


constant values. A list of the most common values is given in Table 2.2.
Table 3.2 Predefined constant values

pi The π number, π = 3.14159 . . .


i,j The imaginary unit i, √−1
Inf The infinity, ∞
NaN Not a number
We illustrate here some typical examples which related to the elementary functions previously
defined.
As a first example, the value of the expression y = e−a sin(x) + 10√y, for a = 5, x = 2, and
y = 8 is computed by

>> a = 5; x = 2; y = 8;
>> y = exp(-a)*sin(x)+10*sqrt(y)
y =
28.2904
The subsequent examples are

>> log(142)
ans =
4.9558

>> log10(142)
ans =
2.1523
Note the difference between the natural logarithm log(x) and the decimal logarithm (base
10) log10(x).
To calculate sin(π/4) and e10, we enter the following commands in MATLAB,
>>sin(pi/4)
ans =
0.7071
>> exp(10)
ans =
2.2026e+004
Notes:
15
• Only use built-in functions on the right hand side of an expression. Reassigningthe
valuetoabuilt-infunctioncancreateproblems.
• Therearesomeexceptions.Forexample,iandjarepre-assignedto√ −1.However,
one or both of ior jare often used as loop indices.
• Toavoidanypossibleconfusion,itissuggestedtouseinsteadiiorjjasloopindices.
3.1.2 User Defined functions/ function files
 A MATLAB function file (called as Extended M-file) is a text (plain ASCII) file that
contains a MATLAB function and, optionally, comments.
 The file is saved with the function name and the usual MATLAB script file extension,
".m".
 A MATLAB function may be called from the command line or from any other M-file.
 When the function is called in MATLAB, the file is accessed, the function is executed, and
control is returned to the MATLAB workspace.
 Since the function is not part of the MATLAB workspace, its variables and their values are
not known after control is returned.
 Any values to be returned must be specified in the function syntax.
 The syntax for a MATLAB function definition is:
Function [val1, val2, … , valn] = myfunc (arg1,arg2, … , argk)
where val1 through valn are the specified returned values from the function and arg1
through argk are the values sent to the function.
 Since variables are local in MATLAB (as they are in C), the function has its own memory
locations for all of the variables and only the values (not their addresses) are passed
between the MATLAB workspace and the function.
 It is OK to use the same variable names in the returned value list as in the argument. The
effect is to assign new values to those variables.
As an example, the following slide shows a function that swaps two values.
function [ a , b ] = swap ( a , b )
temp=a;
a=b;
b=temp;
 To use the function a MATLAB program could assign values to two variables (the names
do not have to be a and b) and then call the function to swap them.
For instance the MATLAB commands:
>> x = 5 ; y = 6 ; [ x , y ] = swap ( x , y )
result in:
x =
6
y=
5
Note: 1) variables created in the function are not retained in the workspace, except for the output
variables.
2) The function does not have access to workspace variables, except for the inputs.
3) variables passed to the function are “copies” of the workspace variables. Changing their
value inside the function has no effect on their value in the workspace.
3.2 Vectors and Matrices
Matrices are the basic elements of the MATLAB environment. A matrix is a two-
dimensional array consisting of m rows and n columns. Special cases are column vectors (n = 1)
and row vectors (m = 1).
In this section we will illustrate how to apply different operations on matrices. The following
topics are discussed: vectors and matrices in MATLAB, the inverse of a matrix, determinants,
16
and matrix manipulation.
MATLAB supports two types of operations, known as matrix operations and array operations.
Matrix operations will be discussed first.
3.2.1 Matrix generation
Matrices are fundamental to MATLAB. Therefore, we need to become familiar with matrix
generation and manipulation. Matrices can be generated in several ways.
3.2.1.1 Entering a vector
A vector is a special case of a matrix. The purpose of this section is to show how to create
vectors and matrices in MATLAB. As discussed earlier, an array of dimension 1 × n is called a
row vector, whereas an array of dimension m × 1 is called a column vector. The elements of
vectors in MATLAB are enclosed by square brackets and are separated by spaces or by commas.
For example, to enter a row vector, v, type
>> v = [1 4 7 10 13]
v =
1 4 7 10 13
Column vectors are created in a similar way, however, semicolon (;) must separate the
components of a column vector,
>> w = [1;4;7;10;13]
w =
1
4
7
10
13
On the other hand, a row vector is converted to a column vector using the transpose operator.
The transpose operation is denoted by an apostrophe or a single quote (’).
>> w = v’
w =
1
4
7
10
13
Thus, v(1) is the first element of vector v, v(2) its second element, and so forth.
Furthermore, to access blocks of elements, we use MATLAB’s colon notation (:). For example, to
access the first three elements of v, we write,

>> v(1:3)
ans =
1 4 7

Or, all elements from the third through the last elements,

>> v(3,end)
ans =
7 10 13

where end signifies the last element in the vector. If v is a vector, writing

>> v(:)
produces a column vector, whereas writing
>> v(1:end)
17
produces a row vector.
3.2.1.2 Entering a matrix
A matrix is an array of numbers. To type a matrix into MATLAB you must
 begin with a square bracket, [
 separate elements in a row with spaces or commas (,)
 use a semicolon (;) to separate rows
 end the matrix with another square bracket, ].
Here is a typical example. To enter a matrix A, such as,

type,
>> A = [1 2 3; 4 5 6; 7 8 9]
MATLAB then displays the 3 × 3 matrix as follows,
A =
1 2 3
4 5 6
7 8 9

Note that the use of semicolons (;) here is different from their use mentioned earlier to suppress
output or to write multiple commands in a single line.
Once we have entered the matrix, it is automatically stored and remembered in the
Workspace. We can refer to it simply as matrix A. We can then view a particular element in a
matrix by specifying its location. We write,
>> A(2,1)
ans= 4
A(2,1) is an element located in the second row and first column. Its value is 4.
3.2.2 Matrix indexing

We select elements in a matrix just as we did for vectors, but now we need two indices.
The element of row i and column j of the matrix A is denoted by A(i,j). Thus, A(i,j) in MATLAB
refers to the element Aij of matrix A. The first index is the row number and the second index is
the column number. For example, A(1,3) is an element of first row and third column. Here,
A(1,3)=3.
Correcting any entry is easy through indexing. Here we substitute A(3,3)=9 by A(3,3)=0. The
result is

>> A(3,3) = 0
A =
1 2 3
4 5 6
7 8 0

Single elements of a matrix are accessed as A(i,j), where i ≥ 1 and j ≥ 1. Zero or negative
subscripts are not supported in MATLAB.
3.2.2.1 Colon operator
The colon operator will prove very useful and understanding how it works is the key to efficient
and convenient usage of MATLAB. It occurs in several different forms.
Often we must deal with matrices or vectors that are too large to enter one ele- ment at a
18
time. For example, suppose we want to enter a vector x consisting of points
(0, 0.1, 0.2, 0.3, · · · , 5). We can use the command
>> x = 0:0.1:5;
The row vector has 51 elements.
3.2.2.2 Linear spacing
On the other hand, there is a command to generate linearly spaced vectors: linspace. It is similar
to the colon operator (:), but gives direct control over the number of points. For example,

y = linspace(a,b)
generates a row vector y of 100 points linearly spaced between and including a and b.
y = linspace(a,b,n)
generates a row vector y of n points linearly spaced between and including a and b. This is useful
when we want to divide an interval into a number of subintervals of the same length. For
example,
>> theta = linspace(0,2*pi,101)
divides the interval [0, 2π] into 100 equal subintervals, then creating a vector of 101 elements.
3.2.2.3 Colon operator in a matrix
The colon operator can also be used to pick out a certain row or column. For example, the
statement A(m:n,k:l specifies rows m to n and column k to l. Subscript expressions refer to
portions of a matrix.
For example,
>> A(2,:)
ans =
4 5 6
is the second row elements of A.
The colon operator can also be used to extract a sub-matrix from a matrix A.

>> A(:,2:3)
ans =
2 3
5 6
8 0
A(:,2:3) is a sub-matrix with the last two columns of A.
A row or a column of a matrix can be deleted by setting it to a null vector, [ ].

>> A(:,2)=[]
ans =
1 3
4 6
7 0
3.2.2.4 Creating a sub-matrix
To extract a submatrix B consisting of rows 2 and 3 and columns 1 and 2 of the matrix A, do the
following

>> B = A([2 3],[1 2]) B


=
4 5
7 8
To interchange rows 1 and 2 of A, use the vector of row indices together with the colon operator.
>> C = A([2 1 3],:) C
=
4 5 6
19
1 2 3
7 8 0
It is important to note that the colon operator (:) stands for all columns or all rows. To create a
vector version of matrix A, do the following
>> A(:)
ans =
1
2
3
4
5
6
7
8
0
The submatrix comprising the intersection of rows p to q and columns r to s is denoted by
A(p:q,r:s).
As a special case, a colon (:) as the row or column specifier covers all entries in that row or
column; thus
• A(:,j) is the jth column of A, while
• A(i,:) is the ith row, and
• A(end,:) picks out the last row of A.
The keyword end, used in A(end,:), denotes the last index in the specified dimension. Here are
some examples.

> A
> =
A 1 2 3
4 5 6
7 8 9

>> A(2:3,2:3)
ans =
5 6
8 9

>> A(end:-1:1,end) ans


=
9
6
3
>> A([1 3],[2 3])
ans =
2 3
8 9
3.2.2.5 Deleting row or column
To delete a row or column of a matrix, use the empty vector operator, [ ].
>> A(3,:) = [] A
=
1 2 3
2
0
4 5 6
Third row of matrix A is now deleted. To restore the third row, we use a technique for creating a
matrix
>> A = [A(1,:);A(2,:);[7 8 0]]
A =
1 2 3
4 5 6
7 8 0
Matrix A is now restored to its original form.

3.2.3 Matrix operations and properties


3.2.3.1 Dimension
To determine the dimensions of a matrix or vector, use the command size. For example,
>> size(A)
ans =
3 3
means 3 rows and 3 columns.
Or more explicitly with,
>> [m,n]=size(A)

3.2.3.2 Continuation
If it is not possible to type the entire input on the same line, use consecutive periods, called an
ellipsis . . ., to signal continuation, then continue the input on the next line.

B = [4/5 7.23*tan(x) sqrt(6); ...


1/x^2 0 3/(x*log(x)); ...
x-7 sqrt(3) x*sin(x)];

Note that blank spaces around +, −, = signs are optional, but they improve readability.
3.2.3.3 Transposing a matrix
The transpose operation is denoted by an apostrophe or a single quote (’). It flips a matrix about
its main diagonal and it turns a row vector into a column vector. Thus,
>> A’
ans =
1 4 7
2 5 8
3 6 0
By using linear algebra notation, the transpose of m × n real matrix A is the n × m matrix
that results from interchanging the rows and columns of A. The transpose matrix is denoted
AT .
3.2.3.4 Concatenating matrices
Matrices can be made up of sub-matrices. Here is an example. First, let’s recall our previous
matrix A.
A =
1 2 3
4 5 6
7 8 9

The new matrix B will be,


21
>> B = [A 10*A; -A [1 0 0; 0 1 0; 0 0 1]] B
=
1 2 3 10 20 30
4 5 6 40 50 60
7 8 9 70 80 90
-1 -2 -3 1 0 0
-4 -5 -6 0 1 0
-7 -8 -9 0 0 1
3.2.4 Matrix generators
MATLAB provides functions that generates elementary matrices. The matrix of zeros, the matrix
of ones, and the identity matrix are returned by the functions zeros, ones, and eye, respectively.
Table 3.3: Elementary matrices

eye(m,n) Returns an m-by-n matrix with 1 on the main diagonal


eye(n) Returns an n-by-n square identity matrix
zeros(m,n) Returns an m-by-n matrix of zeros
ones(m,n) Returns an m-by-n matrix of ones
diag(A) Extracts the diagonal of matrix A
rand(m,n) Returns an m-by-n matrix of random numbers
For a complete list of elementary matrices and matrix manipulations, type help elmat
or doc elmat.
Here are some examples:

1. >> b=ones(3,1)
b =
1
1
1
Equivalently, we can define b as >> b=[1;1;1]
2. >> eye(3)
ans =
1 0 0
0 1 0
0 0 1
3. >> c=zeros(2,3)
c =
0 0 0
0 0 0
In addition, it is important to remember that the three elementary operations of ad- dition
(+), subtraction (−), and multiplication (∗) apply also to matrices whenever the
dimensions are compatible.
Two other important matrix generation functions are rand and randn, which generate
matrices of (pseudo-)random numbers using the same syntax as eye.
In addition, matrices can be constructed in a block form. With C defined by C = [1 2; 3
4], we may create a matrix D as follows

22
3.2.5 Special matrices
MATLAB provides a number of special matrices (see Table 2.5). These matrices have inter-
esting properties that make them useful for constructing examples and for testing algorithms. For
more information, see MATLAB documentation.
Table 3.4: Special matrices

hilb Hilbert matrix


invhilb Inverse Hilbert matrix
magic Magic square
pascal Pascal matrix
toeplitz Toeplitz matrix
vander Vandermonde matrix
wilkinson Wilkinson’s eigenvalue test matrix
3.3 Flow control
MATLAB is also a programming language. Like other computer programming languages,
MATLAB has some decision making structures for control of command execution. These
decision making or control flow structures include for loops, while loops, and if-else-end
constructions. Control flow structures are often used in script M-files and function M-files.
By creating a file with the extension .m, we can easily write and run programs. We do not need to
compile the program since MATLAB is an interpretative (not compiled) language. MATLAB has
thousand of functions, and you can add your own using m-files.
MATLAB provides several tools that can be used to control the flow of a program (script or
function). In a simple program as shown in the previous Chapter, the commands are executed one
after the other. Here we introduce the flow control structure that make possible to skip commands
or to execute specific group of commands.
Knowing relational and logical operators is prerequisite before studying control flow. A relational
operator compares two numbers by determining whether a comparison is true
or false. Relational operators are shown in Table 3.5.
Table 3.5: Relational and logical operators

Operator Description

> Greater than


< Less than
>= Greater than or equal
<= to than or equal to
Less
== Equal to
∼= Not equal to
& AND operator
| OR operator

~ NOT operator
Not Operator
Note that the “equal to” relational operator consists of two equal signs (==) (with no space
23
between them), since = is reserved for the assignment operator.
MATLAB has four control flow structures: the if statement, the for loop, the while loop, and the
switch statement.
3.3.1 The ‘‘if...end’’ structure
MATLAB supports the variants of “if” construct.
• IF , IF ELSE , IF ELSEIF ELSE are conditional statements
• In a conditional statement a conditional expression is stated.
• If the expression is true, a group of commands that follow the statement is
executed.
• If the expression is false, the computer skips the group
• IF Control Syntax and flow chart

• IFELSE Control Syntax and flow chart

• IF - ELSEIFControl Syntax and flow chart

• IF ladder

24
Here are some examples based on the familiar quadratic formula.

1. discr = b*b - 4*a*c; if discr < 0


disp(’Warning: discriminant is negative, roots are imaginary’);
end

2. discr = b*b - 4*a*c; if discr < 0


disp(’Warning: discriminant is negative, roots are imaginary’);
else
disp(’Roots are real, but may be repeated’)
end

3. discr = b*b - 4*a*c; if discr < 0


disp(’Warning: discriminant is negative, roots are imaginary’);
elseif discr == 0
disp(’Discriminant is zero, roots are repeated’) else
disp(’Roots are real’)
end
It should be noted that:
• elseif has no space between else and if (one word)
• no semicolon (;) is needed at the end of lines containing if, else, end
• indentation of if block is not required, but facilitate the reading.
• the end statement is required
3.3.2 The ‘‘for...end’’ loop
In the for ... end loop, the execution of a command is repeated at a fixed and predeter-
mined number of times.
The syntax is
for variable = expression
statements
end
Usually, expression is a vector of the form i:s:j. A simple example of for loop is
for ii=1:5
x=ii*ii
end
It is a good idea to indent the loops for readability, especially when they are nested. Note that
MATLAB editor does it automatically.
Multiple for loops can be nested, in which case indentation helps to improve the readability.
The following statements form the 5-by-5 symmetric matrix A with (i, j) element
25
i/j for j ≥ i:
n = 5; A = eye(n); for
j=2:n
for i=1:j-1
A(i,j)=i/j;
A(j,i)=i/j;
end
end

3.3.3 The ‘‘while...end’’ loop


This loop is used when the number of passes is not specified. The looping continues until a stated
condition is satisfied. The while loop has the form:

while expression
statements
end

The statements are executed as long as expression is true.


x =1
while x <= 10
x = 3*x
end
It is important to note that if the condition inside the looping is not well defined, the looping will
continue indefinitely. If this happens, we can stop the execution by pressing Ctrl-C.
3.3.4 The Switch
• SWITCH switch among several cases based on expression.
• The switch expression can be a scalar or a string.
• A flag (any variable ) is used as switch and the value of the flag make up the different cases
for execution.

3.3.5 Other flow structures(Branching and Braking)


26
• The break statement. A while loop can be terminated with the break statement, which
passes control to the first statement after the corresponding end. The break statement
can also be used to exit a for loop.
• The continue statement can also be used to exit a for loop to pass immediately to the
next iteration of the loop, skipping the remaining statements in the loop.
• It's easy to confuse the break, continue, and return functions as they are similar in some
ways.
• Make sure you use these functions appropriately.

27
3.4 Plotting
• The basic commands that MATLAB uses to draw the graph of a function of a
variable are as follows:
plot(X,Y)
draws the set of points (X, Y), where X and Y are row vectors.
• For graphing a function y = f (x), it is necessary to know a set of points (X, f (X)),
to set a range of variation for the vector X. X and Y can be matrices of the same
size, in which case a graph is made by plotting each pair of rows and on the same
axis.
• For complex values of X and Y, the imaginary parts are ignored.
plot (Y)
draws the vector Y elements, i.e., gives the graph of the set of points (t, Yt) fort = 1,
2,… n where n = length (Y). It is useful for graphing time series. If Y is a matrix,
plot(Y) makes a graph for each column Y presenting all on the same axis. If the
components of the vector are complex, plot (Y) is equivalent to plot (real (Y), imag
(Y)).
• For line colors and styles
plot (X, Y, 'S')
draws plot(X,Y) with the settings defined in S. Usually, S consists of two symbols
between single quotes, the first of which sets the color of the line of the graph and
the second sets the character to be used in the plotting.
plot(X1,Y1,S1,X2,Y2,S2,X3,Y3,S3,…)
combines, on the same axes, graphs defined for the triplets(Xi, Yi, Si). It is a way of
representing various functions on the same graph.
fplot(function, [xmin, xmax])
graphs the function for the variation of x over the given range.
fplot(function, [xmin, xmax, ymin, ymax], S)
graphs the function over the range xmin toxmax while limiting the y-axis to the
range of ymin to ymax, with options for color, line style, and markers given by S.
fplot([f1,f2,…,fn],[xmin, xmax, ymin, ymax], S)
graphs functions f1, f2,…, fn on the same axes at intervals for the range of x and y
specified, and the color, line, and marker styles defined in S.
ezplot (‘expression’, [xminxmax])
graphs the expression for the variation of x given in the range.
Let’s see some examples of 2-dimensional graphics:
It may be useful to differentiate between curves by their strokes, for instance if you
cannot assume that your ultimate user of the graph can print in color. For variety, in
Figure 3 we represent the first function, Sine (x), with a black line, the second, Sine(2x),
using blue star, and the third, Sine (3x), with red circles. We use the following syntax:
x = (0:0.05:2*pi);
y1 = sin(x); y2 = sin(2*x); y3 = sin(3*x);
plot(x,y1,'k-',x,y2,'b*',x,y3,'ro');

3.4.1 Addingtitles,axislabels,andannotations
MATLAB enables you to add axis labels and titles. For example, using the graph from
the previous example, add an x- and y-axis labels.
Now label the axes and add a title. The character \pi creates the symbol π. An
example of 2D plot is shown in Figure 3.2.

Figure 3.2: Plot of the Sine function


>> xlabel(’x = 0:2\pi’)
>> ylabel(’Sine of x’)
>> title(’Plot of the Sine function’)
Thecolorofasinglecurveis,bydefault,blue,butothercolorsarepossible.
Thedesired
colorisindicatedbyathirdargument.Forexample,redisselectedbyplot(x,y,’r’
).Note thesinglequotes,’’,aroundr.
3.4.2 Multiple data sets in oneplot : multiple plots
Multiple(x,y)pairsargumentscreatemultiplegraphswithasinglecalltoplot.
Forexample, these statements plot three related functions of x: y1 = 2
cos(x), y2 = cos(x), and y3 =
0.5 ∗cos(x), in the interval 0 ≤ x ≤ 2π.
x = 0:pi/100:2*pi;
y1 = 2*cos(x);
y2 = cos(x);
y3 = 0.5*cos(x);
plot(x,y1,’--’,x,y2,’-’,x,y3,’:’)
xlabel(’0 \leq x \leq 2\pi’)
ylabel(’Cosine functions’)
legend(’2*cos(x)’,’cos(x)’,’0.5*cos(x)’)
title(’Typical example of multiple plots’)
axis([0 2*pi -3 3])
The result of multiple data sets in one graph plot is shown in Figure 3.3.

Figure 3.3: Typical example of multiple plots

By default, MATLAB uses line style and color to distinguish the data sets
plotted in the graph. However, you can change the appearance of these graphic
components or add annotations to the graph to help explain your data for
presentation.
3.4.3 Subplots
Present in the same figure the graphs of the functions Sin(x) and Cos (x), placed
horizontally one next to each other with their names, with the x axis values between 0
and 2 * pi, a shaft, and taking y values between - 1 and 1.Also get the vertical
representation, so that they one under the other and use slotted shafts.
x = (0:0.1:2*pi);
y = sin(x);
z = cos(x);
subplot(1,2,1);
plot(x,y), axis([0, 2*pi, -1, 1]), title('sin(x)')
subplot(1,2,2);
plot(x,z), axis([0, 2*pi, -1, 1]), title('cos(x)')
3.4.4 Specifyinglinestylesandcolors
It is possible to specify line styles, colors, and markers (e.g., circles, plus signs, .
. . ) using the plot command:
plot(x,y,’style_color_marker’)
where style_color_marker is a triplet of values from Table 3.6.
To find additional information, type help plot or doc plot.
Table 3.6: Attributes for plot

Symbol Color Symbol LineStyle Symbol Marker

k Black − Solid + Plussign


r Red −− Dashed o Circle
b Blue : Dotted ∗ Asterisk
g Green −. Dash-dot . Point
c Cyan none Noline × Cross
m Magenta s Square
y Yellow d Diamond

3.4.5 Types of MATLAB Plots


You can construct a wide variety of 2-D and 3-D MATLAB plots with very little, if
any, programming required on your part. The following two tables classify and
illustrate most of the kinds of plots you can create. They include line, bar, area,
direction and vector field, radial, and scatter graphs. They also include 2-D and 3-D
functions that generate and plot geometric shapes and objects. Most 2-D plots have 3-
D analogs, and there are a variety of volumetric displays for 3-D solids and vector
fields. Plot types that begin with "ez" (such as ezsurf) are convenience functions that
can plot arguments given as functions.
3.4.5.1 Two-Dimensional Plotting Functions
The Fig.3.5 below shows all available MATLAB 2-D plot functions. If you are
reading this online, you can 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.
3.4.5.2 Three-Dimensional Plotting Functions
The Fig.3.6 below shows all available MATLAB 3-D and volumetric plot functions.
It includes functions that generate 3-D data (cylinder, ellipsoid, sphere), but most plot
either arrays of data or functions. If you are reading this online, you can click any
picture in the table to see the documentation for that function. For information about
and examples of using 3-D plotting functions, see Creating 3-D Graphs in the 3-D
Visualization documentation.

____________________________________________________________________

UNIT –IV

Micro Syllabus:
Symbolic Math, Linear Algebra, Polynomials-roots, Optimization-minimization and
maximization, Differentiation/Integration, Differential Equations and Examples

4.0 Symbolic math

Matlab has a powerful symbolic math ability. Rather than making calculations on known
numbers , we can make calculations on symbolic expressions. The key function in matlab
to create a symbolic representation of data is: sym() or syms.

1. Defining symbolic expressions:


2. We can define symbolic functions using the sym and syms commands.
3. Ex: create an expression a*x^2+b*x+c

>>syms a b c x

>>f= a*x^2+b*x+c

4. Evaluation of symbolic expression:

The key function subs(which stands for substitute) is used to replace symbolic variables
with new symbolic variables.
Syntax: subs(symbolic function, list of variables, list of values)

Ex:>> f= sym(‘a*x^2+b*x+c’)

>>subs(f,x,5)

>>subs(f, [x a b c], [5 1 2 3])

4.1 Linear algebraic equations

Linear algebraic equations occur in almost all branches of numerical analysis. But their
most visible application in engineering is in the analysis of linear systems (any system
whose response is proportional to the input is deemed to be linear). Linear systems
include structures, elastic solids, heat flow, seepage of fluids, electromagnetic fields and
electric circuits; i.e., most topics taught in an engineering curriculum.

If the system is discrete, such as a truss or an electric circuit, then its analysis leads
directly to linear algebraic equations. In the case of a statically determinate truss, for
example, the equations arise when the equilibrium conditions of the joints are written
down. The unknowns x1, x2, . . . ,xnrepresent the forces in the members and the support
reactions, and the constants b1, b2, . . . , bn are the prescribed external loads.

The behavior of continuous systems is described by differential equations, rather than


algebraic equations. However, because numerical analysis can deal only with discrete
variables, it is first necessary to approximate a differential equation with a system of
algebraic equations. The well-known finite difference, finite element and boundary
element methods of analysis work in this manner. They use different approximations to
achieve the “discretization, but in each case the final task is the same:

solve a system(often a very large system) of linear, algebraic equations. In summary, the
modeling of linear systems invariably gives rise to equations of the form Ax = b, where b
is the input and x represents the response of the system.

The coefficient matrix A, which reflects the characteristics of the system, is independent
of the input. In other words, if the input is changed, the equations have to be solved again
with a different b, but the same A. Therefore, it is desirable to have an equation-solving
algorithm that can handle any number of constant vectors with minimal computational
effort.

Asystemofalgebraicequationshastheform

A11x1 + A12x2 +···+A1nxn = b1

A21x1 + A22x2 +···+A2nxn = b2

A31x1 + A32x2 +···+A3nxn = b3

An1x1 + An2x2 +···+Annxn = bn

where the coefficients Aij and the constants bj areknown, and xi represent the
unknowns.In matrix notationtheequationsarewritten as

[A1 A12. . .A1n¿][A21 A2. . . A2n¿][. . .¿][. . .¿][. . .¿] ¿


¿
or, simply AX=B

For example if :
Given a system of linearequations

x+2y-3z=5

-3x-y+z=-8

x-y+z=0

Construct matrices so the system is described byAx=b

» A=[1 2 -3;-3 -1 1;1 -11];


» b=[5;-8;0];

And solve with a single line ofcode!

» x=A\b; 0r

» x=inv(A)*b;

x is a 3x1 vector containing the values of x, y, andz

The \ will work with square or rectangularsystems.Gives least squares solution for
rectangular systems. Solution depends on whether the system is over orunderdetermined.

4.2 Linear Algebra

 Calculate the rank of a matrix


r=rank(mat);

 the number of linearly independent rows or columns

 Calculate the determinant


d=det(mat);

 mat must be square


 if determinant is nonzero, matrix is invertible

 Get the matrix inverse


E=inv(mat);
 if an equation is of the form A*x=b with A a square matrix, x=A\b is the
same as x=inv(A)*b
For example:

Given a system of linear equations

x+4y=34

-3x+y=2

Above equations can be represented by as AX=B


A=[1 2;-3 1];

B=[34;2];

>>det(A)

>>rank(A)

>>x=inv(A)*B

For example to solve the following system of equations

System1:

x + 4y = 34

-3x +y = 2

Above equations can be represented as


» A=[1 4;-31];

» b=[34;2];

» rank(A)

» x=inv(A)*b;
System2:

2x - 2y = 4

-x +y = 3

3x + 4y =2

Above equations can be represented as

» A=[2 -2;-1 1;34];


» b=[4;3;2];

» rank(A)

 rectangularmatrix
» x1=A\b;
 gives least squares solution
» error=abs(A*x1-b)
4.2.1 Matrix Decompositions
A matrix decomposition is a factorization of a matrix in to some canonical form.
MATLAB has built-in matrix decompositionmethods. The most common onesare

LU decomposition

» [L,U]=lu(X)
>>L*U=X
 Where L and U are lower and Upper triangular matrices.
Eigenvaluedecomposition
» [V,D]=eig(X)
>>V*D=X
Singular valuedecomposition

» [U,S,V]=svd(X)
>>U*S*V’=A
 where U and V are unitary matrices and S is a diagonal matrix with non negative
elements in the decreasing order.
QRdecomposition

» [Q,R]=qr(X)
>>Q*R=A
 where Q is an orthogonal matrix and R is an upper triangular matrix

4.3 Polynomials

 Many functions can be well described by a high-order polynomial

 MATLAB represents a polynomials by a vector of coefficients ordered by

desending powers.

if vector P describes a polynomialax3+bx2+cx+d


P=[1 0 -2] represents the polynomial x2-2

P=[2 0 0 0] represents the polynomial 2x3

4.3.1 Polynomial Operations

P is a vector of length N+1 describing an N-th order polynomial.


To get the roots of a polynomial
»r=roots(P)
where r is a vector of length N
Can also get the polynomial from the roots
»P=poly(r)
where r is a vector length N
To evaluate a polynomial at a point
»y0=polyval(P,x0)
where x0 is a single value; y0 is a single value
To evaluate a polynomial at many points
»y=polyval(P,x)
wherex is a vector; y is a vector of the same size
4.3.2 Polynomial Fitting

MATLAB makes it very easy to fit polynomials to data

Given data vectors X=[-1 0 2] and Y=[0 -1 3]

»p2=polyfit(X,Y,2);

 finds the best second order polynomial that fits the points (-1,0),(0,-1), and (2,3)

 see help polyfitfor more information


»plot(X,Y,’o’, ‘MarkerSize’, 10);

»hold on;

»x = -3:.01:3;

»plot(x,polyval(p2,x), ‘r--’);
For example :

Evaluating y=x^2 for x=-4:0.1:4.

»x=-4:0.1:4;

»y=x.^2;•

Add random noise to these samples. Use randn. Plot the noisy signal with .markers

»y=y+randn(size(y));

»plot(x,y,’.’);•

Fit a 2nddegree polynomial to the noisy data»

»p=polyfit(x,y,2);•

Plot the fitted polynomial on the same plot, using the same x values and a red line»

»hold on;

»plot(x,polyval(p,x),’r’)

4.4 Optimization

Optimization tool box provides functions for finding parameters that minimize or
maximize objectives while satisfying constraints.

 Many real-world problems require us to solvef(x)=0

 Can use fzero to calculate roots for any arbitraryfunction


 fzero needs a function passed toit.

 We will see this more and more as we delve intosolving


equations.

 Make a separate functionfile

» x=fzero('myfun',1)

» x=fzero(@myfun,1)

 fminbnd: minimizing a function over a boundedinterval


» x=fminbnd('myfun',-1,2);

o myfun takes a scalar input and returns a scalaroutput

o myfun(x) will be the minimum of myfun for -1x 2


 fminsearch: unconstrainedinterval

» x=fminsearch('myfun',.5)

o finds the local minimum of myfun starting atx=0.5

 You do not have to make a separate functionfile

» x=fzero(@myfun,1)

o What if myfun is reallysimple?

 Instead, you can make an anonymousfunction

» x=fzero(@(x)(cos(exp(x))+x^2-1),
);
» x=fminbnd(@(x)(cos(exp(x))+x^2-1),-1,2);

4.5 Numerical Differentiation


Differentiation is an operation that allows us to find function that outputs the rate of change
of one variable w.r.t another variable.
MATLABcan 'differentiate'numerically

» x=0:0.01:2*pi;

» y=sin(x);

» dydx=diff(y)./diff(x);

where “diff” computes the firstdifference

 Can also operate onmatrices

» mat=[1 3 5;4 86];


» dm=diff(mat,1,2)

o first difference of mat along the 2nddimension, dm=[2 2;4-2]


o The opposite of diffis the cumulative sum cumsum

 2Dgradient

» [dx,dy]=gradient(mat);

4.6 NumericalIntigration
Numerical Integration of One Variable
Method Function Decription Propert
y
Trapezoida trapz(X,Y) Computes the integral of High
l Method Y with respect to X using speed,
trapezoidal integration. low
e.g., accurac
X = 0:pi/100:pi; y
Y = sin(X);
Z = trapz(X,Y)
Recursive quad(fun,a,b) approximate the integral Higher
adaptive of function fun from a to accurac
Simpson b to within an error of y
quadrature 1e-6. fun is a function
handle.
e.g.,
F = @(x)1./(x.^3-2*x-5);
Q = quad(F,0,2);
Multiple Integral
Double dblquad(fun,xmin,xmax,ymin,ymax) Calls the quad function  
integral to evaluate the double
integral fun(x,y) over the
rectangle xmin<= x <=
xmax, ymin<= y <=
ymax. fun is a function
handle.
e.g.,
F = @(x,y)y*sin(x)
+x*cos(y);
Q
= dblquad(F,pi,2*pi,0,pi)
;
Triple triplequad(fun,xmin,xmax,ymin,ymax,zmin,zma evaluates the triple
integral x) integral fun(x,y,z) over
the three dimensional
rectangular region
xmin<= x <= xmax,
ymin<= y <= ymax,
zmin<= z <= zmax. fun is
a function handle.
e.g.,
F= @(x,y,z)y*sin(x)
+z*cos(x);
Q= triplequad(F,0,pi,0,1,
-1,1);

4.7 Differential Equations

Use dsolve to compute symbolic solutions to ordinary differential equations. You can


specify the equations as symbolic expressions containing diff or as strings with the
letter Dto indicate differentiation.
Before using dsolve, create the symbolic function for which you want to solve an
ordinary differential equation. Use sym or syms to create a symbolic function. For
example, create a function y(x):
syms y(x)
To specify initial or boundary conditions, use additional equations. If you do not specify
initial or boundary conditions, the solutions will contain integration constants, such
as C1, C2, and so on.
The output from dsolve parallels the output from solve. That is, you can:
 Call dsolve with the number of output variables equal to the number of
dependent variables.
 Place the output in a structure whose fields contain the solutions of the

differential equations.

Format:
[t, YY]=solver (‘Func’,tspan,Y0)
Func: name of ODE function
tspan: A vector specifying the interval of integration, [t0,tf]. For tspan vectors
withtwo elements [t0 tf], the solver returns the solution evaluated at every
integration step.

For tspan vectors with more than two elements, the solver returns solutions
evaluated at the given timepoints. The time values must be in order, either
increasing or decreasing.
Y0: A vector of initial conditions.

4.7.1 First-Order Linear ODE


Suppose you want to solve the equation y'(t) = t*y. First, create the symbolic
function y(t):
syms y(t)
Now use dsolve to solve the equation:
y(t) = dsolve(diff(y,t) == t*y)
y(t) =C2*exp(t^2/2)
y(t) = C2*exp(t^2/2) is a solution to the equation for any constant C2.
Solve the same ordinary differential equation, but now specify the initial condition y(0)
= 2:

syms y(t)
y(t) = dsolve(diff(y,t) == t*y, y(0) == 2)
y(t) =2*exp(t^2/2)

4.7.2Nonlinear ODE
Nonlinear equations can have multiple solutions, even if you specify initial conditions.
For example, solve this equation:
syms x(t)
x(t) = dsolve((diff(x,t) + x)^2 == 1, x(0) == 0)
results in
x(t) = exp(-t) - 1
1 - exp(-t)
4.7.3 Second-Order ODE with Initial Conditions
Solve this second-order differential equation with two initial conditions. One initial
condition is a derivative y'(x) at x = 0. To be able to specify this initial condition,
create an additional symbolic function Dy = diff(y). (You also can use any valid
function name instead of Dy.) Then Dy(0) = 0 specifies that Dy = 0 at x = 0.
syms y(x)
Dy = diff(y);
y(x) = dsolve(diff(y, x, x) == cos(2*x) - y, y(0) == 1, Dy(0) == 0);
y(x) = simplify(y)
y(x) =1 - (8*sin(x/2)^4)/3
4.7.4 Third-Order ODE
Solve this third-order ordinary differential equation:
3 3=u
d u/dx


u(0)=1,  u′(0)=−1,  u′ (0)=π,

Because the initial conditions contain the first- and the second-order derivatives, create
two additional symbolic functions, Dy and D2y to specify these initial conditions:
syms u(x)
Du = diff(u, x);
D2u = diff(u, x, 2);
u(x) = dsolve(diff(u, x, 3) == u, u(0) == 1, Du(0) == -1, D2u(0) == pi)
u(x) =(pi*exp(x))/3 - exp(-x/2)*cos((3^(1/2)*x)/2)*(pi/3 - 1) -...
(3^(1/2)*exp(-x/2)*sin((3^(1/2)*x)/2)*(pi + 1))/3

UNIT –V

Micro Syllabus: Probability and Statistics, Data Structures, Images and Animation,Debugging
and Online Resource

5.1 Statistics
Statistical Functions
MATLAB has built-in functions for many statistics; the simplest of which we have already seen;
for example, min and max to find the minimum or maxi-mum value in a data set.

x = [9 10 10 9 8 7 3 10 9 8 5 10];
min(x)
ans =
3
>> max(x)

ans =
10
Both of these functions also return the index of the smallest or largest value; if there is more than
one occurrence, it returns the first. For example, in the following data set, 10 is the largest value;
it is found in three elements in the vector but the index returned is the first element in which it is
found (which is 2):

x = [9 10 10 9 8 7 3 10 9 8 5 10];
[maxval, maxind] = max(x)

maxval =
10
maxind =
2
For matrices, the min and max functions operate columnwise by default:

>> mat = randint(2,4,[1 20])

mat =

9 10 17 5
19 9 11 14

>> min(mat)

ans=5

• Whenever analyzing data, you have to computestatistics

» scores =100*rand(1,100);

• Built-infunctions

 mean, median,mode
• To group data into ahistogram

» hist(scores,5:10:95);

 makes a histogram with bins centered at 5, 15,25…95

» N=histc(scores,0:10:100);

 returns the number of occurrences between the specified bin


edges 0 to <10, 10 to <20…90 to <100. you can plot
thesemanually:

» bar(0:10:100,N,'r')

5.1.1 Random Numbers

• Many probabilistic processes rely on randomnumbers


• MATLAB contains the common distributions builtin
» rand

 draws from the uniform distribution from 0 to1

» randn

 draws from the standard normal distribution(Gaussian)

» random

 an give random numbers from many moredistributions

 see doc random forhelp

 the docs also list other specific functions

• You can also seed the random numbergenerators

rand('state',0);rand(1);rand(1
);rand('state',0);rand(1);

For matrices: mean(), std(), var(), median(), cov()

Most of the above commands can be applied to matrices. Use each column as one
data vector. Assume that M ∈ R N×m is a matrix of m column vectors with N
values in each column.

>>mean(M) :compute the average of each column. The result is a row vector with
m components.

>>std(M) :compute the standard deviation of each column. The result is a row
vector with m components.

>>Mode(m):
The mode of a data set is the value that appears most frequently. The built-in function in
MATLAB for this is called mode.

x = [9 10 10 9 8 7 3 10 9 8 5 10];

mode(x)

ans =
10
>>var(M) compute the variance of each column. The result is a row vector with m
components.

>>median(M) compute the median value of each column. The result is a row
vector with m components. To describe the effect of cov() and corr() first step
is to assure that the average of each column equals zero. Mm = M − ones (N,
1 )∗mean(M) ; Observe that this operation does not change the variance of the
column vectors.

>>cov(M) determines the m × m covariance matrix

5.1.2 Changing mean and variance

• We can alter the givendistributions


» y=rand(1,100)*10+5;

 gives 100 uniformly distributed numbers between 5 and15


» y=floor(rand(1,100)*10+6);

 gives 100 uniformly distributed integers between 10and


15
 floor or ceil is better to use here than round

5.2 Probability
• We will simulate Brownian motion in 1 dimension. Call the script
‘brown’.
• Make a 10,000 element vector ofzeros.
• Write a loop to keep track of the particle’s position at eachtime.

• Start at 0. To get the new position, pick a random number, and if it’s
<0.5, go left; if it’s >0.5, go right. Store each new position in the
kthposition in thevector.

• Plot a 50 bin histogram of thepositions.

x=zeros(10000,1);
forn=2:10000

ifrand<0.5

x(n)=x(n-1)-1;

else

x(n)=x(n-1)+1;

end

end
figure;

hist(x,50);

5.3 Advanced Data Structures

Engineers need to manipulate large amountsof data


• Data sometimes comes in a variety of formats
• Data is both numeric and character or “string”data
• Matlab has two important structures that youshould be familiar with:
• Struct arrays
• Cell arrays

 We have used 2Dmatrices

 Can haven-dimensions

 Every element must be the same type (ex. integers,


doubles,characters…)
 Matrices are space-efficient and convenient forcalculation
 Large matrices with many zeros can be madesparse:
» a=zeros(100); a(1,3)=10;a(21,5)=pi;b=sparse(a);
Sometimes, more complex data structures aremore appropriate

5.3.1 Cell array:Cell arrays are similar to regular arrays in that they are
"indexed" lists of data, with a symbolic name. Unlike traditional arrays, a cell
array can contain a different data type in every "bucket". These buckets are
called "cells".

Cell arrays in Matlab use the curly bracket {} notation instead of the normal
parentheses (). While you may think that using () works, it in fact returns the
"cell" of the array, not the "value" of the cell

5.3.1 a) Cells-Organization

 A cell is just like a matrix, but each field cancontain anything even

othermatrices):

 One cell can contain people's names, ages, and the agesof theirchildren.

 To do the same with matrices, you would need 3variables andpadding.

b) Cells-initialization

 To initialize a cell, specify thesize


» a=cell(3,10);

o a will be a cell with 3 rows and 10columns


 or do it manually, with curly braces{}
» c={'hello world',[1 5 62],rand(3,2)};

o c is a cell with 1 row and 3columns


 Each element of a cell can beanything
Manipulation of cell arrays:
 To access a cell element, use curly braces{}
>> c={'hello world',[1 5 6 2],rand(3,2)}
c=
'hello world' [1x4 double] [3x2 double]
>>c{1}
ans =
hello world
>>c{2}
ans =
1 5 6 2
>>c(2)
ans =
[1x4 double]

5.3.2 Structs
A Structure is a collection of data representing a single idea or "object". For anything in a
computer more complicated than a list of numbers, structures can be used. Inside a
structure are a list of fields each being a variable name for some sub-piece of data.
Structures are similar to arrays in that they contain multiple data, but the main difference
is, instead of an Index to each piece of data, we have a "name"; and instead of every piece
of data being the same type, we can have a different type for each "field".

 Structs allow you to name and bundle relevantvariables

o Like C-structs, which are objects withfields


 To initialize an emptystruct:

o » s=struct([]);

o size(s) will be1x1

o initialization is optional but is recommended when using


large structs
 To addfields

o » s.name = 'JackBauer';

 » s.scores = [95 9867];

 » s.year ='G3';

o Fields can be anything: matrix, cell, evenstruct


o Useful for keeping variablestogether

5.3.2.1 Struct: Arrays

 To initialize a struct array, give field, valuespairs

» ppl=struct('name',{'John','Mary','Leo'},...
'age',{32,27,18},'childAge',{[2;4],1,[]});

o size(s2)=1x3

o every cell must have the samesize

» person=ppl(2);

o person is now a struct with fields name, age,children

o the values of the fields are the second index into eachcell

» person.name

o returns'Mary'

» ppl(1).age

o returns32

ppl ppl(1)ppl(2)ppl(3)

name: 'John' 'Mary''Leo'


age: childAge: 32 2718
[2;4] 1[]

5.3.2.1 Struct: Access

 To access 1x1 struct fields, give name of thefield

» stu=s.name;
» scor=s.scores;
o 1x1 structs are useful when passing many variables to a
function. put them all in a struct, and pass thestruct
 To access nx1 struct arrays, useindices

» person=ppl(2);

o person is a struct with name, age, and childage

» personName=ppl(2).name;

o personName is'Mary'

» a=[ppl.age];

o a is a 1x3 vector of the ages; this may not always work, the
vectors must be able to beconcatenated.

For example

 Write a script calledsentGen

 Make a 3x2 cell, and put three names into the firstcolumn, and adjectives
into the secondcolumn

 Pick two random integers (values 1 to3)

 Display a sentence of the form '[name] is[adjective].'

 Run the script a fewtimes

c=cell(3,2);

c{1,1}=‘John’;c{2,1}=‘Mary-Sue’;c{3,1}=‘Gomer’;

c{1,2}=‘smart’;c{2,2}=‘blonde’;c{3,2}=‘hot’

r1=ceil(rand*3);r2=ceil(rand*3);

disp([ c{r1,1}, ' is ', c{r2,2}, '.']);

5.4 Images

 Every graphics object has ahandle


» L=plot(1:10,rand(1,10));

o gets the handle for the plottedline

» A=gca;

o gets the handle for the currentaxis

» F=gcf;

o gets the handle for the currentfigure

 To see the current property values, useget

» get(L);
» yVals=get(L,'YData');

 To change the properties, useset

» set(A,'FontName','Arial','XScale','log');
» set(L,'LineWidth',1.5,'Marker','*');

 Everything you see in a figure is completelycustomizable


throughhandles

5.4.1 Reading/writing Images


The simplest way to read an image is to store the image in the current
directory(workspace)of MATLAB using the function imread as follows

 Images can be imported into matlab

» im=imread('myPic.jpg');

 Image stored in MATLAB work space in the form of matrix.


 In order to show the stored image in the figure window we use the command
>>Imshow(im)

 MATLAB supports almost all imageformats

o jpeg, tiff, gif, bmp, png, hdf, pcx, xwd, ico, cur, ras, pbm,
pgm,ppm
o see help imread for a full list anddetails
>> size(im)
780 360 3
780 indicates height and 360 indicates width of the image
and 3 indicates colours RGB.
>>im(:,:,[1 3])=0
>>Imshow(im)
 The above command gives green color image.
 To write an image, give an rgb matrix or indicesand
colormap
» imwrite(rand(300,300,3),'test1.jpg');

» imwrite(ceil(rand(200)*256),jet(256),...
'test2.jpg');

o see help imwritefor moreoptions

5.5 Animations
Process of creating continuous motion and shape change illusion.

Animation is used for data representation of dynamics of a systems & good

visual impact

 MATLAB makes it easy to capture movie frames and play them back

automatically
 The most common movie formats are:
 AVI
 animated gif

 AVI: good when you have ‘natural’ frames with lots of colors and few clearly
defined edges

 Animated GIF: Good for making movies of plots or text where only a few
colors exist (limited to 256) and there are well-defined lines.
5.5.1 Making Animations
There are 3 facilities available to create animation in MATLAB.
1. Comet:
 It is similar to plot command
 We can animate 2D/3D plots
 Comet head moves along the curve and tail traces the line connecting
data points.

Command syntax:

>>comet(x,y)

Where x and y are predefined vectors to be plotted.

EX: animating a lone y= 0.5*x+5 in the range of x=[0 10]

>> x=0:0.001:10

>> y= 0.5*x+5

>>comet(x,y)

Figure window will open and you will see a curve being plotted.

Limitation: Simple but we can animate curves only.

2. Handle Graphics
Floating point number assigned by MATLAB every entity in figure window
which can be used address for that entity. MATLAB gives handle to every
entity automatically handles can also be given by users as
>>hl=plot(x,y)
Commands related to handle:
get(hl)-lists all properties related to handle and its values.
To change entity properties
Set(handle, ’property name’, ’property value’)

Program for animation of bed rotating in circular path


%A bed rotatingarond the circumference of circle
clf
theta=0:0.001:2*pi
x=cos(theta)
y=sin(theta)
hbead=line(x(1),y(1),'marker','o','markersize',10)
axis([-1 1 -1 1])
axis('square')
for k=2:length(theta)
set(hbead,'xdata',x(k),'ydata',y(k))
drawnow
end
3. Movies

If you have a sequence of plots that you would like to animate, use the built-in
function movie. The basic idea to store each figure as frame of the movie with
each frame stored as column vector of big matrix say M and then to play the
frames on the screen with the command movie (M)

 A frame is stored in column vector using the command getframe.


 Built-in command movie in is provided precisely for this initialization.
Movie(frames, m ,fps)
Which plays a movie stored in frames m times at the rate of fps
frames/second.

Ex: Plot frame by frame, and pause inbetween

closeall

for t=1:30

imagesc(rand(200));

colormap(gray);

pause(.5);

end

Can also use drawnowinstead ofpause

When plotting lines or points, it's faster tochangethexdataand


ydataproperties rather than plotting each time

»h=plot(1:10,1:10);

»set(h,'ydata',10:1);
Saving Animations as movies
• A movie is a series of capturedframes

closeall

forn=1:30

imagesc(rand(200));

colormap(gray);

M(n)=getframe;

end

• To play a movie in a figurewindow

movie(M,2,30);

Loops the movie 2 times at 30 frames persecond

• To save as an .avi file on your harddrive


movie2avi(M,'testMovie.avi','FPS',30,...'compression','cinepak');

5.5.3Making Animation GIF's


• You can use imwrite to save an animated GIF. Below isa
trivialexample
» temp=ceil(rand(300,300,1,10)*256);

» imwrite(temp,jet(256),'testGif.gif','delaytime',0.1,'loopcount',100);

• Alternatively, you can use getframe, frame2im, and rgb2ind to


convert any plotted figure to an indexed image and then stack these
indexed images into a 4-D matrixand pass them to imwrite. Read the
doc on imwriteand these other functions to figure out how to dothis.

5.6 Debugging

This section introduces general techniques for finding errors in M-files. Debugging is
the process by which you isolate and fix errors in your program or code.
Debugging helps to correct two kinds of errors:

• Syntax errors - For example omitting a parenthesis or misspelling a function


name.

• Run-time errors - Run-time errors are usually apparent and difficult to track
down. They produce unexpected results.
5.6.1 Debuggingprocess
We can debug the M-files using the Editor/Debugger as well as using debugging
functions from the Command Window. The debugging process consists of
• Preparing for debugging

• Setting breakpoints

• Running an M-file with breakpoints

• Stepping through an M-file

• Examining values

• Correcting problems

• Ending debugging

5.6.2 Preparing for debugging


Here we use the Editor/Debugger for debugging. Do the following to prepare for
debugging:

• Open the file

• Save changes

• Be sure the file you run and any files it calls are in the directories that are on the
search path.

5.6.3 Setting breakpoints


Set breakpoints to pause execution of the function, so we can examine where the
problem might be. There are three basic types of breakpoints:

• A standard breakpoint, which stops at a specified line.


• A conditional breakpoint, which stops at a specified line and under specified
conditions.

• An error breakpoint that stops when it produces the specified type of warning,
error, NaN, or infinite value.
You cannot set breakpoints while MATLAB is busy, for example, running an M-file.

5.6.4 Running with breakpoints


After setting breakpoints, run the M-file from the Editor/Debugger or from the
Command Window. Running the M-file results in the following:

• The prompt in the Command Window changes to

K>>

thatindicates MATLAB is in debug mode.

• The program pauses at the first breakpoint. This means that line will be executed
when you continue. The pause is indicated by the green arrow.

• In breakpoint, we can examine variable, step through programs, and run other
calling functions.

5.6.5 Examining values


While the program is paused, we can view the value of any variable currently in the
workspace. Examine values when we want to see whether a line of code has produced
the expected result or not. If the result is as expected, step to the next line, and continue
running. If the result is not as expected, then that line, or the previous line, contains an
error. When we run a program, the current workspace is shown in the Stack field. Use
who or whos to list the variables in the current workspace.

5.6.5.1 Viewing values as datatips


First, we position the cursor to the left of a variable on that line. Its current value
appears. This is called a datatip, which is like a tooltip for data. If you have trouble
getting the datatip to appear, click in the line and then move the cursor next to the
variable.
5.6.6 Correcting and ending debugging
While debugging, we can change the value of a variable to see if the new value
produces expected results. While the program is paused, assign a new value to the
variable in the Com- mand Window, Workspace browser, or Array Editor. Then
continue running and stepping through the program.

5.6.7 Ending debugging


After identifying a problem, end the debugging session. It is best to quit debug mode
before editing an M-file. Otherwise, you can get unexpected results when you run the
file. To end debugging, select Exit Debug Mode from the Debug menu.

5.6.8 Correcting an M-file


To correct errors in an M-file,
• Quit debugging
• Do not make changes to an M-file while MATLAB is in debug mode
• Make changes to the M-file
• Save the M-file
• Clear breakpoints
• Run the M-file again to be sure it produces the expected results.

5.6.9 Steps involved in Debugging


• When debugging functions, use disp to printmessages

disp('startingloop')

disp('loop isover')

 disp prints the given string to the command window


• It's also helpful to show variablevalues

disp(strcat(['loop iteration',num2str(n)]));

 strcat concatenates the givenstrings

 Sometimes it's easier to just remove somesemicolons


• To use the debugger, setbreakpoints
 Click on – next to line numbers in MATLABfiles

 Each red dot that appears is abreakpoint

 Run theprogram

 The program pauses when it reaches abreakpoint

 Use the command window to probe variables

 Use the debugging buttons to controldebugger


• Use the debugger to fix the errors in the followingcode:

5.6.10Performance Measures

• It can be useful to know how long your code takes torun


 To predict how long a loop will take
 To pinpoint inefficientcode
• You can time operations usingtic/toc:
» tic

» CommandBlock1

» a=toc;

» CommandBlock2
» b=toc;

Note:1) tic resets thetimer

2) Each toc returns the current value inseconds

3) Can have multiple tocs pertic

• For more complicated programs, use theprofiler


» profileon

 Turns on the profiler. Follow this with functioncalls

» profileviewe

UNIT –VI
Micro Syllabus: Symbolic Math, Simulink, File I/O, Graphical User Interfaces

6.1 Symbolic Math ToolBox

Matlab has a powerful symbolic math ability. Rather than making calculations on
known numbers , we can make calculations on symbolic expressions. The key function in
matlab to create a symbolic representation of data is: sym() or syms.

Symbolics vs.Numerics

Advantages Disadvantages
•Sometimes can't be
•Analytical solutions solved.
Symbolic •Lets you intuit things •Can be overly
about solution form complicated.

•Hard to extract a
•Always get a solution deeper understanding.
•Can make solutions •Num. methods
Numeric
accurate sometimes fail
•Easy to code •Can take a while to
Compute.

5. Defining symbolic expressions:

Symbolic variables are a type, like double orchar.


We can define symbolic functions using the sym and syms commands.

 To make symbolic variables, usesym


» a=sym(1/3);
» b=sym(4/5);
»mat=sym([1 2;34]);
 Multiply, add, subtract, divideexpressions
>> m=a*b m=1/12
>> m=a+b m=7/12
>> m=a-b m=1/12
>> m=a/b m=4/3

Ex: create an expression a*x^2+b*x+c

>>syms a b c x

>>f= a*x^2+b*x+c

6. Evaluation of symbolic expression:

The key function subs(which stands for substitute) is used to replace symbolic variables
with new symbolic variables.

Syntax: subs(symbolic function, list of variables, list of values)

Ex:>> f= sym(‘a*x^2+b*x+c’)

>>subs(f,x,5)

>>subs(f, [x a b c], [5 1 2 3])

7. Symbolic Operations
We can do symbolics with matricestoo

» mat=sym('[a b;cd]');
compute theproduct

» mat2=mat*[1
3;4-2];

compute thedeterminant

» d=det(mat)

find the inverse

» i=inv(mat)
You can access symbolic matrix elements asbefore

» i(1,2

6.2 SIMULINK

Simulink is a graphical extension to MATLAB for modeling and simulation of systems.


One of the main advantages of Simulink is the ability to model a nonlinear system, which
a transfer function is unable to do. Another advantage of Simulink is the ability to take on
initial conditions. When a transfer function is built, the initial conditions are assumed to
be zero.

Simulink is started from the MATLAB command prompt by entering the following
command:

>>simulink

Alternatively, you can hit the Simulink button at the top of the MATLAB window as
shown here:

When it starts, Simulink brings up a single window, entitled Simulink Library Browser
which can be seen here

Basic Elements

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

Blocks

There are several general classes of blocks within the Simulink library:

 Sources: used to generate various signals


 Sinks: used to output or display signals
 Continuous: continuous-time system elements (transfer functions, state-space
models, PID controllers, etc.)
 Discrete: linear, discrete-time system elements (discrete transfer functions,
discrete state-space models, etc.)
 Math Operations: contains many common math operations (gain, sum, product,
absolute value, etc.)
 Ports & Subsystems: contains useful blocks to build a system etc.

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

6.1.1 Creating Simulink model:

To create new Simulink model click

file new model

 Drag the required blocks from the simulink library browser to the simulink model.

 The following simple model consists of three blocks: Step, Transfer Function,
and Scope.

 The Step is a Source block from which a step input signal originates. This signal
is transferred through the line in the direction indicated by the arrow to the
Transfer FunctionContinuous block.

 The Transfer Function block modifies its input signal and outputs a new signal
on a line to the Scope.

 The Scope is a Sink block used to display a signal much like an oscilloscope.

 There are many more types of blocks available in Simulink. Right now, we will
examine just the three we have used in the simple model.
In order to obtain output double click on scope button after execute the run button. The
step response of first order transfer function is as follows.

6.3 FILE I/O

6.3.1 Input/Output operations in MATLAB:


In this section we present examples of input and output operations in Matlab.
Saving and loading variables.
To save all current active variables in a file use the command save. Let's try an example:

clear <enter>
A = [1 2 3; -3 4 5; 2 4 5; 1 3 2]; b = 1:10; <enter>
A <enter>
b <enter>
save Data<enter>

Here file uses the suffix .mat. Next, using the text editor ( File>Open, then select file)
open the file DataAB.mat in sub-directory work of MATLAB. You will notice that you
cannot see the numbers in the file. That is because they have been saved in a binary
format. Let's clear the variables in MATLAB and re-load the values of A and b using the
command load:

clear <enter>
who <enter>
load Data<enter>
A <enter>
b <enter>

Recall that the command who lists all active variables in Matlab. Function save will save
all current active variables in Matlab with the name you have given them. Function load
will load the variables in a mat file with the appropriate names.

Unformatted output to the screen


To print strings and single variables to the screen, without a format, you can use the disp
function. The general form of the function is: disp (sting or variable_name). Try the
following examples:

x = 5; y = sin(pi*x/10); r = 1:2:25; A = rand(5,3); <enter>


disp(‘x = ’), disp(x) <enter>
disp(‘y : ’),disp(y) <enter>
disp(‘vector r is’), disp(r) <enter>
disp(‘matrix A is’), disp(A)<enter>

6.3.2 Working with files


You can write data to a file or read data from a file by using functions fprintf and fscanf,
respectively. These functions are similar to their counterparts of the same name in C, C++, or
C#. In order to access a file, however, you must first open it with functionfopen. To close afile
after reading or writing data, use function fclose. Examples of the use of these functions are
shown next.

Function fopen
The general form of function fopen is:

file_id = fopen(filename, permission)

where file_id is a variable name to be used as reference to the file, filename is an appropriate
file name reference, e.g., ‘c:\file1.txt’, and permission is a string representing one of the
following actions:

'r' read
'w' write (create if necessary)
'a' append (create if necessary)
'r+' read and write (do not create)
'w+' truncate or create for read and write
'a+' read and append (create if necessary)
'W' write without automatic flushing
'A' append without automatic flushing

There are other forms of calling function fopen. For more details, use the command
help fopen

Suppose that we want to create a new file called c:\results1.txt so that we can write data into
it. We could use to produce this file the command:

myFile = fopen('c:\results1.txt','w') <return>

Notice that Matlab responds with the output:

myFile =

indicating that variable myFile has been assigned the value 3. If you were to open a second
file, its file_id will be assigned the number 4, and so on.

Printing to the Matlab interface with fprintf


File id numbers 0, 1, and 2 correspond to pre-defined devices. For example, file id numbers 1
and 2, or no file id, produce output in the Matlab interface. Try the following examples:

fprintf(1,'hello world! \n') <return>

x = 3.2; fprintf('The value of x is %f \n',x) <return>

In these two examples we have used function fprintf which prints a string, i.e., the contents
between quotes. Parts of the printed string are specifications such as \n or %f known as C
conversion specifications. For example, the conversion specification \n indicates to start a new
line, while the conversion specification %f indicates that a floating-point field should be
included to take the value of variable(s) listed at the end of the string in the fprintf function.
More details and examples of using function fprintf are shown below.

Function fclose
The general form of function fclose is:

status = fclose(filename)
where status is a numerical variable that can take the value 0 if the file closing operation is
successful, or -1 if it is not successful (e.g., the file wasn’t open in the first place, or the file
doesn’t exist). For example, having open file c:\results1.txt, as shown earlier, we can close
this file by using either

fclose(myFile) <return>

or

fclose(3)

In both cases, Matlab responds with the result:

ans =

0
Function fprintf
The general form of function fprintf is

fprintf(file_id, format_string, variables)

where file_id is a variable or number referring to a file open with function fopen, or to the
Matlab interface (i.e., file _id = 1 or 2), format_string is a string containing characters or
conversion specifications, and variables is an optional list of variables. The following
examples show uses of function fprintf to print to the Matlab interface, although the same
examples can be used to write to a text file.

Printing a string with function fprintf


Function fprintf can be used to print simply a string, e.g., a title for a text file:

fprintf('\n ---- Output File for Program "Open_Channel" ---- \n\n') <return>

Recall that the conversion specification \n produces a new line (linefeed), thus, the result of
this command will be shown in Matlab as follows:

» fprintf('\n ---- Output File for Program "Open_Channel" ---- \n\n') [return]

- Output File for Program "Open_Channel" ----

Format specifications for printing control


The “slash” format specifications are used to control the printed output. Here is the
description of these specifications taken from the Matlabhelp fprintf command:

“The special formats \n,\r,\t,\b,\f can be used to produce linefeed, carriage


return, tab, backspace, and form-feed characters respectively.”

Also,
“Use \\ to produce a backslash character and %% to produce the percent
character.”

Here is an example using some of these format specifications:


» fprintf('\nUse \\n to produce a line feed \t\t and these are two tabs.\n\n')
[return]
Use \n to produce a line feed and these are two tabs.

»
Format specifications for integer values
The format specification %i allows to replace the value of an integer variable. For example:

» i2 = 5; jj = -102;
» fprintf('\nInteger indices: i2 = %i and jj = %i\n\n',i2,jj)

Integer indices: i2 = 5 and jj = -102

If the variables actually contain floating-point values (i.e., values with decimal parts), the
integer format specifications will be replaced by scientific notation formats, e.g.,

» i2 = 6.23; jj = -102.45;
» fprintf('\nInteger indices: i2 = %i and jj = %i\n\n',i2,jj)

Integer indices: i2 = 6.230000e+000 and jj = -1.024500e+002

NOTE: If you are not familiar with scientific notation format, the results above represent i2 =
6.23×100 and jj = -1.0245×102. Thus, the notation a.aa…ebbb, in general, represents the
number a.aa… ×10yyy.
One can specify the width of the integer field to assign to an integer value (i.e., the number of
spaces allowed), for example:

» i2 = 5; jj = -102;
» fprintf('\nInteger indices: i2 = %5i and jj = %10i\n\n',i2,jj)

Integer indices: i2 = 5 and jj = -102

In this case, variable i2 was assigned 5 positions, but only one is needed, thus 4 positions are
left blank leaving a larger space between the characters = and 5 in the output. Similarly,
variable jj requires only 4 positions for output, but 10 positions are assigned (%5i), thus,
leaving 6 leading blanks before the value –102.

If you don’t provide enough positions for an integer output, fprintf will force a minimum
number of spaces to print the correct output. For example, in the following specification for
variable jj only two positions are provided (%2i), but the value requires 4 positions, thus,
fprintfforces the field to have a minimum of 4 positions.

» i2 = 5; jj = -102;
» fprintf('\nInteger indices: i2 = %2i and jj = %2i\n\n',i2,jj)

Integer indices: i2 = 5 and jj = -102

%f format specifications for floating point values


The format specification %f allows to replace the value of floating-point variables. For
example:

» x = 123.45; y = -0.00056;
» fprintf('\nReal variables: x = %f and y = %f\n\n',x,y)
Real variables: x = 123.450000 and y = -0.000560

Notice that the specification %f shows floating-point values with six decimal places. You can
control the number of integer and decimal places by using the specification %w.df, where w is
the total number of positions in the output (i.e., the width of the field) and d is the number of
decimal positions. To ensure plenty of positions available for your output, make sure that
w≥d+3, three being the minimum number of spaces required beyond the decimal part (i.e.,
oneposition for a sign, one for an integer digit, and one for the decimal point). Here is an
example using f formats with specified number of decimals and field width:

» x = 123.45; y = -0.00056;
» fprintf('\nReal variables: x = %7.2f and y = %9.5f\n\n',x,y)

Real variables: x = 123.45 and y = -0.00056

If you don’t specify enough decimals for a field, the information printed may be truncated. For
example, variable y in the following example, shows only zeros in the decimal part because
only 2 decimal positions were specified:

» x = 123.45; y = -0.00056;
» fprintf('\nReal variables: x = %7.2f and y = %7.2f\n\n',x,y)

Real variables: x = 123.45 and y = -0.00


»

In the following example, even though the field for variable x, in principle, does not have
enough width to show all the integer digits, fprintf expands the field width to show all of
them:

» x = 123.45; y = -0.00056;
» fprintf('\nReal variables: x = %5.2f and y = %7.5f\n\n',x,y)

Real variables: x = 123.45 and y = -0.00056

Using d = 0 will truncate the values to be printed to their integer parts, e.g.,

» x = 123.45; y = -0.00056;
» fprintf('\nReal variables: x = %5.0f and y = %7.0f\n\n',x,y)

Real variables: x = 123 and y = -0


»

%e format specifications for floating point values


The format specification %e allows to replace the value of floating-point variables using
scientific notation. For example:

» x = 123.45; y = -0.00056;
» fprintf('\nReal variables: x = %e and y = %e\n\n',x,y)

Real variables: x = 1.234500e+002 and y = -5.600000e-004


»

The default field for scientific notation format shows one integer digit, six decimal digits, and
three integer digits for the exponent. Also, positions are allowed within the field for signs on
the integer part and on the exponent, and one position for the decimal point.

One can specify the width of the field (w) and the number of decimals (d) by using the
specification %w.de, for example:

» x = 123.45; y = -0.00056;
» fprintf('\nReal variables: x = %e and y = %e\n\n',x,y)

Real variables: x = 1.234500e+002 and y = -5.600000e-004

Since we need to allow for three positions for the exponent, one for the exponent’s sign, one
for the integer-part sign, one for one integer position, one for the decimal point, and one for
the sign of the number, we need to have at least w≥d+8.

Using d = 0 truncates the mantissa (i.e., the part that is not the exponent) to an integer, e.g.,

» x = 123.45; y = -0.00056;
» fprintf('\nReal variables: x = %10.0e and y = %13.0e\n\n',x,y)

Real variables: x = 1e+002 and y = -6e-004


»

%g format specifications for floating point values


The format specification %g allows to replace the value of variables according to the most
appropriate format, be it integer, floating-point, or scientific notation. For example:

» m = 2; r = -12.232123; s = 0.00000000000023;
» fprintf('\nSee these values: m = %g, r = %g, and s = %g\n\n',m,r,s)

See these values: m = 2, r = -12.2321, and s = 2.3e-013

Notice that the %g specification chose an integer format for m, a regular floating-point format
for r, and a scientific-notation format for s.

An attempt to provide for field width and number of decimals for the %g format, by using
%10.5g, shows that only the width specification has an effect (i.e., keeping the fields at
awidth of 10 characters):

» m = 2; r = -12.232123; s = 0.00000000000023;
» fprintf('\nSee these values: m = %10.5g, r = %10.5g, and s = %10.5g\n\n',m,r,s)

See these values: m = 2, r = -12.232, and s = 2.3e-01


»

Thus, we may as well have just used %10g in the specification:

» m = 2; r = -12.232123; s = 0.00000000000023;
» fprintf('\nSee these values: m = %10g, r = %10g, and s = %10g\n\n',m,r,s)
See these values: m = 2, r = -12.2321, and s = 2.3e-013

%s specification for strings


The %s format specification can be used to replace the value of a string variable. A string
variable contains text. The following Matlab commands show how to load string variables and
how to use the %s format specification to print out the values of those string variables:

» sname = 'Bart Simpson'; prof = 'daredevil';


» fprintf('\nHis name is %s and he is a %s.\n\n', sname, prof)

His name is Bart Simpson and he is a daredevil.

Additional information about string variables is provided below.

Combining format specifications


Control characters (i.e., \n, \t, etc.) and format specifications (%i, %f, %e, %g, %s, etc.) can be
combined in a fprintf output string to produce output to the Matlab interface or to a file. Here
is an example that combines several specifications:

» fprintf('\nIn iteration no. %2i, x = %g, while y = %f8.2, ...


for case: %s.\n\n', jj, x, y, title)

In iteration no. 5, x = 5.6e-010, while y = -123.4500008.2, for case: Logan


Canal.
»

Scripts for writing to a file


We present two scripts as examples of opening, writing to, and closing a file. In the first script
we only write numerical data.

%Script to write numerical data to a text


file x = 0:1:10; y = sin(x*pi/8); z = exp(x);
myFile = fopen('c:\Results1.txt','w');
n = length(x);
for j = 1:n
fprintf(myFile,'%5i %10.6f %16.8e \n',x(j),y(j),z(j));
end;
fclose(myFile);

Type the script into the Matlab editor and save it as Write1.m. Then run the script, and open
file c:\Results1.txt using the editor. The result is the following file:

1 0.000000 1.00000000e+000
2 0.382683 2.71828183e+000
3 0.707107 7.38905610e+000
4 0.923880 2.00855369e+001
5 1.000000 5.45981500e+001
6 0.923880 1.48413159e+002
7 0.707107 4.03428793e+002
8 0.382683 1.09663316e+003
9 0.000000 2.98095799e+003
10 -0.382683 8.10308393e+003
11 -0.707107 2.20264658e+004
An output like this may be useful for future data analysis. On the other hand, you may
want to produce a fancier output to include in a report. The following example shows such
an output. Type the following script and save it as Write2.m:

%Script to write numerical data to a text


file x = 0:1:5; y = sin(x*pi/8); z =exp(x);
myFilefopen('c:\Results2.txt','w');
n = length(x);
fprintf(myFile,'There were %2i measurements made, with the
following results:\n\n',n);
for j = 1:n
fprintf(myFile,'For time %5i sec., the tide elevation was %10.6f
m,\n', x(j),y(j));
fprintf(myFile,'while the available energy was %16.8e J.
\n',z(j)); end;
fclose(myFile);

After running this script, open file c:\Results2.txt to see the following results:

There were 6 measurements made, with the following results:


For time 0 sec., the tide elevation was 0.000000 m,
while the available energy was 1.00000000e+000 J. m,
For time 1 sec., the tide elevation was 0.382683
while the available energy was 2.71828183e+000 J. m,
For time 2 sec., the tide elevation was 0.707107
while the available energy was 7.38905610e+000 J.
For time 3 sec., the tide elevation was 0.923880 m,
while the available energy was 2.00855369e+001 J.
For time 4 sec., the tide elevation was 1.000000 m,
while the available energy was 5.45981500e+001 J.
For time 5 sec., the tide elevation was 0.923880 m,
while the available energy was 1.48413159e+002 J.
Reading from a data file
The following example shows a simple way to read data from the file Results1.txt created
above. The file contains a matrix of data consisting of 11 rows and 3 columns. The
following script will read the data from the file and separate the columns into three
variables, namely, x, y, z. Save the script under the name Read1.m:

%Script to read data from file "c:\Results1.txt"


%created with script "Write1.m"
fclose('all'); %Ensures all files are closed
myFile = fopen('c:\Results1.txt','r');
R = fscanf(myFile,'%5i %10f %16e',
[3,11]); fclose(myFile);
R = R';%Transpose to make it look like original
table %The next line extract columns
x = R(:,1); y = R(:,2); z = R(:,3)
After executing the script, try the following Maple commands to see the data recovered from the
file:

» R

R =

1.0e+004 *

0 0 0.0001
0.0001 0.0000 0.0003
0.0002 0.0001 0.0007
0.0003 0.0001 0.0020
0.0004 0.0001 0.0055
0.0005 0.0001 0.0148
0.0006 0.0001 0.0403
0.0007 0.0000 0.1097
0.0008 0 0.2981
0.0009 -0.0000 0.8103
0.0010 -0.0001 2.2026

Because of the different orders of magnitude in the data read, the matrix R is shown as being
multiplied by the factor 1.0e+004 (i.e., 1×104). To see the numbers in more detail use:
EDU» format long
EDU» R

R =

1.0e+004 *
0 0 0.00010000000000
0.00010000000000 0.00003826830000 0.00027182818300
0.00020000000000 0.00007071070000 0.00073890561000
0.00030000000000 0.00009238800000 0.00200855369000
0.00040000000000 0.00010000000000 0.00545981500000
0.00050000000000 0.00009238800000 0.01484131590000
0.00060000000000 0.00007071070000 0.04034287930000
0.00070000000000 0.00003826830000 0.10966331600000
0.00080000000000 0 0.29809579900000
0.00090000000000 -0.00003826830000 0.81030839300000
0.00100000000000 -0.00007071070000 2.20264658000000

Use the following commands to see the separated columns:

x <return> y <return> z <return>

The following are things to keep in mind when using the fscanf function to read data in the form
of tables (i.e., data that can be stored in a matrix):

1 Make sure that you know the format in which the data is stored in the input file.

2 Make sure that the file is open with function fopen and that it uses the specification ‘r’
for reading.
3 The general form of the call to function fscanf is:

A = fscanf(file_id, format, size)

where file_id is the reference to the file being read, format is a format string describing the
format of the data columns, and size is a vector of the form [n,m] where n is the number of
columns and m is the number of row in the data matrix.

4 The matrix A that is loaded will be transposed with respect to the data matrix in the file.
Thus, a statement like A = A’ may be used to convert matrix A to the same shape as the data
74
in the file.

5 After matrix A has been loaded, the different columns can be separated as in the script shown
above.

6.4 BUILDING GUIS

Introduction

A graphical user interface (GUI) is a pictorial interface to a program. A good GUI can make
programs easier to use by providing them with a consistent appearance and with intuitive
controls like pushbuttons, list boxes, sliders, menus, and so forth. The GUI should behave in an
understandable and predictable manner, so that a user knows what to expect when he or she
performs an action. For example, when a mouse click occurs on a pushbutton, the GUI should
initiate the action described on the label of the button. This chapter introduces the basic elements
of the MATLAB GUIs. The chapter does not contain a complete description of components or
GUI features, but it does provide the basics required to create functional GUIs for your
programs.

6.4.1 How a Graphical User Interface Works

A graphical user interface provides the user with a familiar environment in which to work. This
environment contains pushbuttons, toggle buttons, lists, menus, text boxes, and so forth, all of
which are already familiar to the user, so that he or she can concentrate on using the application
rather than on the mechanics involved in doing things. However, GUIs are harder for the
programmer because a GUI -based program must be prepared for mouse clicks (or possibly
keyboard input) for any GUI element at any time. Such inputs are known as events, and a
program that responds to events is said to be event driven. The three principal elements required
to create a MATLAB Graphical User Interface are

1. Components. Each item on a MATLAB GUI (pushbuttons, labels, edit boxes, etc.) is a
graphical component. The types of components include graphical controls (pushbuttons, edit
boxes, lists, sliders, etc.), static elements (frames and text strings), menus, and axes. Graphical
controls and static elements are created by the function uicontrol, and menus are created by the
functions uimenu and uicontextmenu. Axes, which are used to display graphical data, are created
by the function axes.

2. Figures. The components of a GUI must be arranged within a figure, which is a window on
the computer screen. In the past, figures have been created automatically whenever we have
plotted data. However, empty figures can be created with the function figure and can be used to
hold any combination of components.

3. Callbacks. Finally, there must be some way to perform an action if a user clicks a mouse on a
button or types information on a keyboard. A mouse click or a key press is an event, and the
MATLAB program must respond to each event if the program is to perform its function. For
example, if a user clicks on a button, that event must cause the MATLAB code that implements
the function of the button to be executed. The code executed in response to an event is known as
a call back. There must be a callback to implement the function of each graphical component on
the GUI. The basic GUI elements are summarized in Table 1.1, and sample elements are shown
in Figure 1.1. We will be studying examples of these elements and then build working GUIs
from them.
75
6.4.2 Graphical User Interface Components

This section summarizes the basic characteristics of common graphical user interface
components. It describes how to create and use each component, as well as the types of events
each component can generate. The components discussed in this section are

• Text Fields
• Edit Boxes
• Frames
• Pushbuttons
• Toggle Buttons
• Checkboxes
• Radio Buttons
• Popup Menus
• List Boxes
• Slide

Text Fields:
A text-field is a graphical object that displays a text string. You can specify how the text is
aligned in the display area by setting the horizontal alignment property. By default, text fields are
horizontally centered. A text field is created by creating a uicontrol whose style property is 'edit'.
A text field may be added to a GUI by using the text tool in the Layout Editor.
Edit boxes:
An edit box is a graphical object that allows a user to enter a text string. The edit box generates a
callback when the user presses the Enter key after typing a string into the box. An edit box is
created by creating a uicontrol whose style property is 'edit'. An edit box may be added to a GUI
by using the edit box tool in the Layout Editor.

Frames

A frame is a graphical object that displays a rectangle on the GUI. You can use frames to draw
boxes around groups of logically related objects.
Pushbuttons

A pushbutton is a component that a user can click on to trigger a specific action. The pushbutton
generates a callback when the user clicks the mouse on it. A pushbutton is created by creating a
uicontrol whose style property is 'pushbutton'. A pushbutton may be added to a GUI by using the
pushbutton tool in the Layout Editor.
Toggle Buttons

A toggle button is a type of button that has two states: on (depressed) and off (not depressed). A
toggle button switches between these two states whenever the mouse clicks on it, and it generates
a callback each time. The 'Value' property of the toggle button is set to max (usually 1) when the
button is on, and min (usually 0) when the button is off.
A toggle button is created by creating a uicontrol whose style property is toggle button. A toggle
button may be added to a GUI by using the toggle button tool in the Layout Editor.
Checkboxes and Radio Buttons
76
Checkboxes and radio buttons are essentially identical to toggle buttons except that they have
different shapes. Like toggle buttons, checkboxes and radio buttons have two states: on and off.
They switch between these two states whenever the mouse clicks on them, generating a callback
each time. The 'Value' property of the checkbox or radio button is set to max (usually 1) when
they are on, and min (usually 0) when they are off.
A checkbox is created by creating a uicontrol whose style property is 'checkbox', and a
radio button is created by creating a uicontrol whose style property is 'radiobutton'. A checkbox
may be added to a GUI by using the checkbox tool in the Layout Editor, and a radio button may
be added to a GUI by using the radio button tool in the Layout Editor. Checkboxes are
traditionally used to display on/off options, and groups of radio buttons are traditionally used to
select among mutually exclusive options.
Popup Menus
Popup menus are graphical objects that allow a user to select one of a mutually exclusive list of
options. The list of options that the user can select among is specified by a cell array of strings,
and the 'Value' property indicates which of the strings is currently selected. A popup menu may
be added to a GUI by using the popup menu tool in the Layout Editor.

List Boxes
List boxes are graphical objects that display many lines of text and allow a user to select one or
more of those lines. If there are more lines of text than can fit in the list box, a scroll bar will be
created to allow the user to scroll up and down within the list box. The lines of text that the user
can select among are specified by a cell array of strings, and the' Value' property indicates which
of the strings are currently selected. A list box is created by creating a uicontrol whose style
property is 'listbox'. A list box may be added to a GUI by using the listbox tool in the Layout
Editor

Sliders
Sliders are graphical objects that allow a user to select values from a continuous range between a
specified minimum value and a specified maximum value by moving a bar with a mouse. The
'Value' property of the slider is set to a value between min and max depending on the position of
the slider.
A slider is created by creating a uicontrol whose style property is 'slider'. A slider may be added
to a GUI by using the slider tool in the Layout Editor.

Dialog Boxes
A dialog box is a special type of figure that is used to display information or to get input from a
user. Dialog boxes are used to display errors, provide warnings, ask questions, or get user input.
They are also used to select files or printer properties. Dialog boxes may be modal or non-modal.
A modal dialog box does not allow any other window in the application to be accessed until it is
dismissed, whereas a non-modal dialog box does not block access to other windows. Modal
dialog boxes are typically used for warning and error messages that need urgent attention and
cannot be ignored. By default, most dialog boxes are non-modal

77
6.4.3 Building GUI

It's really easy to make a graphical user interface in MATLAB • To open the graphical user
interface development environment, type guide
» guide
¾ Select Blank GUI Court
Draw the GUI
• Select objects from the left, and draw them where you want them Change objective
settings
Double-click on objects to open the Inspector. Here you can change all the object's
properties.
Save GUI

• When you have modified all the properties, you can save the GUI
• MATLAB saves the GUI as a .fig file, and generates an MATLAB file!
Add functionality to matlab file

• To add functionality to your buttons, add commands to the 'Callback' functions in the
MATLAB file. For example, whenthe user clicks the Draw Image button, the
drawimage_Callbackfunction will be called and executed
• All the data for the GUI is stored in the handles, so use set and get to get data and change it
if necessary
• Any time you change the handles, save it using guidata
» guidata(handles.Figure1,handles);
Running the GUI
• To run the GUI, just type its name in the command window and the GUI will pop up. The
debugger is really helpful for writing GUIs because it lets you see inside the GUI

78
79

You might also like