MSES Note
MSES Note
Micro Syllabus:
MATLAB, MATLAB System, Starting MATLAB, Quitting MATLAB, Inputting and outputting
methods, File Types, Variables and its Assignment.
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.
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.
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).
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:
Note: To simplify the notation, we will use this prompt, >>, as a standard prompt sign, though
our MATLAB version is for educational purpose.
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
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.
Addition 2 +3
− Subtraction 2−3
* Multiplication 2∗3
/ Division 2/3
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, (|)
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.
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.
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.
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
>> 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.
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.5 Exercises :
Example 1 : plot the function f (x) = (sin(x)) ^ 2 + 2xcos(x) where x varying from -2π to 2π.
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.
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.
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
>> 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
> A
> =
A 1 2 3
4 5 6
7 8 9
>> A(2:3,2:3)
ans =
5 6
8 9
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.
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
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
Operator Description
• IF ladder
24
Here are some examples based on the familiar quadratic formula.
while expression
statements
end
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.
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
____________________________________________________________________
UNIT –IV
Micro Syllabus:
Symbolic Math, Linear Algebra, Polynomials-roots, Optimization-minimization and
maximization, Differentiation/Integration, Differential Equations and Examples
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.
>>syms a b c x
>>f= a*x^2+b*x+c
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)
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.
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
where the coefficients Aij and the constants bj areknown, and xi represent the
unknowns.In matrix notationtheequationsarewritten as
For example if :
Given a system of linearequations
x+2y-3z=5
-3x-y+z=-8
x-y+z=0
» x=A\b; 0r
» x=inv(A)*b;
The \ will work with square or rectangularsystems.Gives least squares solution for
rectangular systems. Solution depends on whether the system is over orunderdetermined.
x+4y=34
-3x+y=2
B=[34;2];
>>det(A)
>>rank(A)
>>x=inv(A)*B
System1:
x + 4y = 34
-3x +y = 2
» b=[34;2];
» rank(A)
» x=inv(A)*b;
System2:
2x - 2y = 4
-x +y = 3
3x + 4y =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
desending powers.
»p2=polyfit(X,Y,2);
finds the best second order polynomial that fits the points (-1,0),(0,-1), and (2,3)
»hold on;
»x = -3:.01:3;
»plot(x,polyval(p2,x), ‘r--’);
For example :
»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,’.’);•
»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.
» x=fzero('myfun',1)
» x=fzero(@myfun,1)
» x=fminsearch('myfun',.5)
» x=fzero(@myfun,1)
» x=fzero(@(x)(cos(exp(x))+x^2-1),
);
» x=fminbnd(@(x)(cos(exp(x))+x^2-1),-1,2);
» x=0:0.01:2*pi;
» y=sin(x);
» dydx=diff(y)./diff(x);
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);
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.
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 =
9 10 17 5
19 9 11 14
>> min(mat)
ans=5
» scores =100*rand(1,100);
• Built-infunctions
mean, median,mode
• To group data into ahistogram
» hist(scores,5:10:95);
» N=histc(scores,0:10:100);
» bar(0:10:100,N,'r')
» randn
» random
rand('state',0);rand(1);rand(1
);rand('state',0);rand(1);
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.
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.
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);
Can haven-dimensions
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.
b) Cells-initialization
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".
o » s=struct([]);
o » s.name = 'JackBauer';
» s.year ='G3';
» ppl=struct('name',{'John','Mary','Leo'},...
'age',{32,27,18},'childAge',{[2;4],1,[]});
o size(s2)=1x3
» person=ppl(2);
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)
» 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);
» 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
Make a 3x2 cell, and put three names into the firstcolumn, and adjectives
into the secondcolumn
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);
5.4 Images
» A=gca;
» F=gcf;
» get(L);
» yVals=get(L,'YData');
» set(A,'FontName','Arial','XScale','log');
» set(L,'LineWidth',1.5,'Marker','*');
» im=imread('myPic.jpg');
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');
5.5 Animations
Process of creating continuous motion and shape change illusion.
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)
>> 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.
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’)
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)
closeall
for t=1:30
imagesc(rand(200));
colormap(gray);
pause(.5);
end
»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
movie(M,2,30);
» imwrite(temp,jet(256),'testGif.gif','delaytime',0.1,'loopcount',100);
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:
• 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
• Examining values
• Correcting problems
• Ending debugging
• Save changes
• Be sure the file you run and any files it calls are in the directories that are on the
search path.
• 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.
K>>
• 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.
disp('startingloop')
disp('loop isover')
disp(strcat(['loop iteration',num2str(n)]));
Run theprogram
5.6.10Performance Measures
» CommandBlock1
» a=toc;
» CommandBlock2
» b=toc;
» profileviewe
UNIT –VI
Micro Syllabus: Symbolic Math, Simulink, File I/O, Graphical User Interfaces
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.
>>syms a b c x
>>f= a*x^2+b*x+c
The key function subs(which stands for substitute) is used to replace symbolic variables
with new symbolic variables.
Ex:>> f= sym(‘a*x^2+b*x+c’)
>>subs(f,x,5)
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)
» i=inv(mat)
You can access symbolic matrix elements asbefore
» i(1,2
6.2 SIMULINK
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:
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.
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.
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.
Function fopen
The general form of function fopen is:
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 =
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.
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)
ans =
0
Function fprintf
The general form of function fprintf is
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.
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]
Also,
“Use \\ to produce a backslash character and %% to produce the percent
character.”
»
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)
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)
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)
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)
» 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)
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)
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)
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)
» x = 123.45; y = -0.00056;
» fprintf('\nReal variables: x = %e and y = %e\n\n',x,y)
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)
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)
» m = 2; r = -12.232123; s = 0.00000000000023;
» fprintf('\nSee these values: m = %g, r = %g, and s = %g\n\n',m,r,s)
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)
» 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
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:
After running this script, open file c:\Results2.txt to see the following results:
» 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
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:
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.
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.
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