MATLAB Basics
Dr. R. K. George
M. S. University of Baroda
rkgeorgemsu@gmail.com
1. INTRODUCTION
( a ) What is MATLAB?
MATLAB is an interactive, matrix-based system for scientific and engineering numerical
computation and visualization. It has the features of high-level programming language. The
word MATLAB stands for MATrix LABoratory. Each entry is taken as a matrix in it, in
particular scalar is considered as a 1 by 1 matrix. MATLAB is available for a number of
operating systems like Windows, Linux, IRIS etc. MATLAB commands are platform
independent. MATLAB was originally written in FORTRAN and is licensed by The Math
Works, Inc,
(http:// www.mathworks.com). The version of MATLAB we use is ver 7. There is a relatively
inexpensive student edition available from Prentice Hall Publishers.
( b ) Advantages of MATLAB over FORTRAN or C.
In languages like FORTRAN & C we have to declare dimensions of matrices used. But, here,
by default each entry is a matrix, therefore dimensioning of a variable is not required. We can
solve complex numerical problems in a fraction of the time required with a programming
language such as FORTRAN or C. MATLAB is also a programmable system. It contains so
many useful algorithms as built-in functions and hence programming itself is easier. The
graphic and multimedia capabilities are also commendable. MATLAB’s ease of use is its best
feature.
APPLICATION ORIENTATION IN ENGINEERING MATHEMATICS
AND MATHEMATICAL MODELING , SV NIT, SURAT Dec 26-30,2006.- 1
( c ) Scope of MATLAB.
MATLAB is recognized as the interactive program for numerical linear algebra and matrix
computation. In industries, MATLAB is used for research and to solve practical engineering
and mathematical problems. Also, in automatic control theory, statistics and digital signal
processing (Time-Series Analysis) one can use MATLAB. It contains over 50 tool boxes.
Each tool box contains collection of functions made for special applications. The following
tool boxes make it useful in soft computing at various industrial and scientific areas:
(i) Neural Networks (ii) Optimization
(iii) Genetic Algorithms (iv) Wavelets
(v) Fuzzy Logic (vi) Control systems
(vii) Signal Processing (viii) Optimization
2. MATLAB GETTING STARTED
By clicking the MATLAB shortcut icon on the desktop of your computer (or selecting from
the program menu) you can access MATLAB. This results in getting MATLAB command
window with its prompt:
>>
with a blinking cursor appearing right of the prompt, telling you that MATLAB is waiting to
perform a mathematical operation you would like to give.
APPLICATION ORIENTATION IN ENGINEERING MATHEMATICS
AND MATHEMATICAL MODELING , SV NIT, SURAT Dec 26-30,2006.- 2
MATLAB has three basic windows as shown in the following figure, namely
(i) MATLAB desktop window,
(ii) Editor window, where we can write, edit and save programs, and
(iii) Figure window which displays 2D and 3D graphs of functions.
The MATLAB desktop window itself has three sub-windows :
(i) command window, where we type commands and run programs,
(ii) current directory window, where all the files in the current directory are listed, and
(iii) command history window, where all previous commands we typed are recorded
even across multiple sessions. If we double click any command in the history
window, the command will be executed in the command window.
APPLICATION ORIENTATION IN ENGINEERING MATHEMATICS
AND MATHEMATICAL MODELING , SV NIT, SURAT Dec 26-30,2006.- 3
2.1 MATLAB as a Simple Calculator
( i ) If you want to add two numbers , say, 7 & 12, type as follows
>> 7+12
and press the ENTER or return key, you see the following output:
ans =
19
Here, ans stands for the answer of computation. Similarly, the following gives product and
difference of these numbers,
>> 7*12 <ENTER>
ans =
84
>> 12-7 <ENTER>
ans =
5
( ii ) If you want to store the values 7 and 12 in MATLAB variables a & b and store the
values of their product and division in c and d, do as follows:
>> a =7 <ENTER>
a=
7
>> b = 12 <ENTER>
b=
12
>> c = a*b <ENTER>
c=
84
>> d = 12/7 <ENTER>
d=
1.7143
The \ operator works a follows:
12 \ 7 is same as 7 / 12.
APPLICATION ORIENTATION IN ENGINEERING MATHEMATICS
AND MATHEMATICAL MODELING , SV NIT, SURAT Dec 26-30,2006.- 4
The basic arithmetic operation are given by:
Operation Symbol Example
Addition + 7+12
a+b
Subtraction - 12-7
a-b
Multiplication * 12*7
a.b
Division / and \ 7\12 = 12/7 = 1.7143;
a/b 7/12=0.5833
Exponential ^ 7^2 = 49.
ab
You can exit MATLAB with the command exit or quit. A computation can be forcefully
stopped with [ctrl-c].
2.2 MATLAB as Scientific Calculator
Variables, Expressions and Statements:
Variables
Variable names must be a single word containing no space and it can have any length.
However, the first 31 characters of a variable name is remembered by matlab . Variable
names are case sensitive and a variable names must start with a letter. Punctuation characters
are not allowed.
Examples: The following variable names are valid.
>> length = 7
>> breadth = 4
>> area_rectangle2 =50
The following variable names are not valid:
>> 1st_length = 8 (it starts with a digit)
>> second length = 10 (space between words not permitted)
>> book’s_price =107 (punctuation characters not allowed).
If the variable name and = sign are omitted, a variable ans (for answer) is automatically
created and the result is assigned to it. There are several built-in mathematical functions like
trigonometric, exponential, logarithmic and arithmetic functions available in MATLAB.
For example sin(2) is evaluated as
>> sin(2)
ans =
APPLICATION ORIENTATION IN ENGINEERING MATHEMATICS
AND MATHEMATICAL MODELING , SV NIT, SURAT Dec 26-30,2006.- 5
0.9093
>> atan(1) (calculates the inverse tangent of 1 )
ans =
0.7854
>> log(2) (calculates the natural logarithm of 2)
ans =
0.6931
>> log10(2) (calculates the common logarithm (base 10) of 2)
ans =
0.3010
>> cosh(5) (calculates the hyperbolic cosine of 5)
ans =
74.2099
>> sqrt(3) ( calculates the square root of 3)
ans =
1.7321
Complex numbers i or j stands for − 1 and pi gives the value of π .
>> c = 1-2i
c=
1.000–2.0000 i
Some functions deals with complex numbers are as follows:
>> abs ( c ) (calculates the absolute value of c)
ans =
2.2361
>> real ( c ) (calculates the real part of c)
APPLICATION ORIENTATION IN ENGINEERING MATHEMATICS
AND MATHEMATICAL MODELING , SV NIT, SURAT Dec 26-30,2006.- 6
ans =
1
>> imag ( c ) (calculates the imaginary part of c)
ans =
-2
>> angle ( c ) (calculates the phase angle of c)
ans =
-1.1071
>>
The following are some of the most commonly used functions:
Trigonometric and Hyperbolic functions Exponential and logarithms.
sin - sine. exp - exponential.
sinh - hyperbolic sine. log - natural logarithm.
asin - inverse sine. log10 - common (base 10) logarithm.
asinh - inverse hyperbolic sine. log2 - base 2 logarithm and dissect
cos - cosine. floating point number.
cosh - hyperbolic cosine. pow2 - base 2 power and scale
acos - inverse cosine. floating point number.
acosh - inverse hyperbolic cosine. sqrt - square root.
tan - tangent. nextpow2 - next higher power of 2
tanh - hyperbolic tangent. Complex numbers.
atan - inverse tangent. abs - absolute value.
atan2 - four quadrant inverse tangent. angle - phase angle.
atanh - inverse hyperbolic tangent. conj - complex conjugate.
sec - secant. imag - complex imaginary part.
sech - hyperbolic secant. real - complex real part.
asec - inverse secant. unwrap - unwrap phase angle.
asech - inverse hyperbolic secant. isreal - true for real array.
csc - cosecant. cplxpair - sort numbers into complex
csch - hyperbolic cosecant. conjugate pairs.
acsc - inverse cosecant.
acsch - inverse hyperbolic cosecant.
cot - cotangent.
coth - hyperbolic cotangent.
acot - inverse cotangent.
acoth - inverse hyperbolic cotangent.
APPLICATION ORIENTATION IN ENGINEERING MATHEMATICS
AND MATHEMATICAL MODELING , SV NIT, SURAT Dec 26-30,2006.- 7
Information about commands , operations and functions are available by typing:
>> help command or
>> lookfor command
and to get menu of help commands type
>> help or
>> helpwin
Expressions
Expressions are composed of operators, functions and variable names. After evaluation the
value is assigned to the variable and displayed.
3 2 − sin(3π )
For example, the following commands evaluates the expressions x = ,
52 + 2 3
and y = e −2π 23 + log(e 2 ) sin 2 (3) .
>> x=(3^2-sin(3*pi))/(5^2+2^(sqrt(3)))
x=
0.3178
>> y=exp(-2*pi*sqrt(23))+log(exp(2))*(sin(3))^2
y=
0.0398
Statements
MATLAB’s statements are of the form:
>> variable_name = expression or
>> expression
Rules for statements:
• A statement is normally terminated with the carriage returns or pressing the enter key.
Example : >> area =pi*r^2 <ENTER>
APPLICATION ORIENTATION IN ENGINEERING MATHEMATICS
AND MATHEMATICAL MODELING , SV NIT, SURAT Dec 26-30,2006.- 8
• A statement can be continued on the next line by typing three consecutive periods
(called an ellipsis) followed by a carriage return.
Example:
>> defined_function = sin(x^2)+x^3*tanh(pi*x) + k*cos(x)*y*sin(x)/…
sqrt(p^2+q^2)
• Several statements can be placed on a single line if separated by commas or
semicolons.
Example >> abc = 23; x=45; rkg =abc*x; output = rkg/abc
• If the last character of a statement is a semicolon, then values of the variable printing
to the screen will be suppressed, but the assignment is still carried out.
Example >> a =10;
Rules of Precedence:
Expressions in statements are evaluated from left to right with
(i) exponential operation having the highest precedence, followed by
(ii) multiplication and division having equal precedence, followed by
(iii) addition and subtraction having equal precedence.
Parentheses can be used to alter this ordering in which case these rules of precedence are
applied within each set of parentheses starting with the innermost set and proceeding
outward.
Recalling the values of defined variables
The most recent values assigned to the variables in the current session can be recalled by
typing the variable names in the command prompt.
For example, if we type a a t the prompt we get the output as :
>> a <ENTER>
a=
7
If you cannot remember the names of the variables, you have used in the current session, you
can use the who command for a list of variables MATLAB has in the current session.
>> who
Your variables are
ans a b c
APPLICATION ORIENTATION IN ENGINEERING MATHEMATICS
AND MATHEMATICAL MODELING , SV NIT, SURAT Dec 26-30,2006.- 9
The command whos will list the variables in the workspace and their size.
>> whos
Name Size Bytes Class
ans 1x1 8 double array
a 1x1 8 double array
b 1x1 8 double array
c 100x100 80000 double array
Grand total is 10003 elements using 80024 bytes.
The command
>> clear
will remove all current variables from the memory of the system.
>> clear a
will clear only the variable a.
To clear the screen and take the prompt >> to the top of the command window , type
>> clc
To recall previous commands, MATLAB uses the cursor keys ←, ↑, →, ↓ on your
keyboard.
↑ - recalls the most recent command to the MATLAB prompt.
↓ - scrolls forward through commands.
← - moves one within a command at the MATLAB prompt.
→
Format Statements
The display of numerical values can have different format as we see below:
>> e = 1/3
e=
0.3333
>> format long (long decimal format)
>> e
e=
0.33333333333333
APPLICATION ORIENTATION IN ENGINEERING MATHEMATICS
AND MATHEMATICAL MODELING , SV NIT, SURAT Dec 26-30,2006.- 10
>> format bank (bank format having 2 decimals)
>> e
e=
0.33
>> format short e (short exponential format)
>> e
e=
3.3333 e-01
>>format long e (long exponential format)
e=
3.33333333333333 e-04
>> format ( default format)
>> e
e=
0.3333
Different formats Value of 15 2
format short 21.2132
format short e 2.1213e+001
format long 21.21320343559643
format long e 2.121320343559643e+001
format short g 21.213
format long g 21.2132034355964
format hex 4035369480174810
format rat 4179/197
format bank 21.21
Functions for rounding and remainder.
The following are a few functions available in MATLAB for rounding and
reminders.
fix - round towards zero. Example. fix(-.4) = 0
floor - round towards minus infinity Example: floor(2.78) = 2.00 .
ceil - round towards plus infinity. Ex. ceil(5.25) = 6.00
round - round towards nearest integer. Ex. round(3.46) = 4.00
mod - modulus (signed remainder after division). mod(-5,3) = 1.00
rem - remainder after division. Ex. mod(5,3) = 2.00
sign - signum. Ex. sign(-5) = -1.00
APPLICATION ORIENTATION IN ENGINEERING MATHEMATICS
AND MATHEMATICAL MODELING , SV NIT, SURAT Dec 26-30,2006.- 11
To suppress the display of output of a command on screen put semicolon ‘;’ after the
command.
>> a=3;
>>
To end a session, type quit or exit at the MATLAB prompt.
>> exit or >> quit
When we log out or exit, MATLAB will lose all the current variables from the memory. To
save the current session, type
>> save
This saves the all current variables to a binary diskfile matlab.mat. When you later re-enter
MATLAB, the command
>> load
will restore the workspace to list former state.
To save only a few variables in to a file, use the following commands.
>> save myoutput.mat a x c (saves the variables a , x and c in a file myoutput.mat)
To recall these variables in the next session enter the command
>> load myoutput
3. WORKING WITH MATRICES AND VECTORS:
MATLAB works with essentially only one kind of objects, that is , a rectangular numerical
matrix with possibly complex entries. All variables represent matrices.
Scalers - 1 by 1 matrix
Row vector - matrix with one row
Column vector - matrix with one column.
If you want to store a matrix 1 2 3 in a variable a in the MATLAB’s current
4 5 6
7 8 9
memory, you type the following in the MATLAB prompt.
>> a = [1 2 3; 4 5 6; 7 8 9] <ENTER>
APPLICATION ORIENTATION IN ENGINEERING MATHEMATICS
AND MATHEMATICAL MODELING , SV NIT, SURAT Dec 26-30,2006.- 12
a=
1 2 3
4 5 6
7 8 9
The rows are separated by semicolons (;) and elements are separated by space or by comma.
That is, the above matrix can also be stored by the following command.
>> a = [1,2,3;4,5,6;7,8,9];
or by the statement
>> a = [
1 2 3
4 5 6
7 8 9 ];
The semicolon at the end of a command suppresses the output.
Transpose of a matrix
The matrix a is transposed and is stored in b by the following command
>> b = a’
b=
1 4 7
2 5 8
3 6 9
The following matrix operations are available in MATLAB
Function Task
+ Addition a+b
- Subtraction a-b
* Multiplication a*b
^ Power a^n
‘ Transpose a’
\ Left Division a\b
/ Right Division a/b
The operations above are valid only if the matrices are compatible for such operations.
APPLICATION ORIENTATION IN ENGINEERING MATHEMATICS
AND MATHEMATICAL MODELING , SV NIT, SURAT Dec 26-30,2006.- 13
Table of some important functions dealing with matrices
Function Task Function Task
norm(a) matrix or vector trace(a) sum of diagonal
norm. elements.
normest(a) estimate the matrix null (a) null space.
2-norm.
rank (a) matrix rank. orth(a) orthogonalization.
det(a) determinant rref(a) reduced row echelon
form.
subspace(a,b) angle between two inv(a) Inverse of the matrix
subspaces generated a
by the columns of a
and b.
eig(a) Eigen values of a [v,d]=eig(a) Provides eigen values
and eigen vectors of a
size(a) Provides the size of pinv(a) Pseudo inverse of a or
the matrix a Moore-Penrose
inverse of A
Examples:
>> a1 = a+b (matrices a and b are added and stores in a1)
a1 =
2 6 10
6 10 14
10 14 18
>> b1 = a-b (b is subtracted from a and stores in b1)
b1 =
0 -2 -4
2 0 -2
4 2 0
>> c = a*b (a is multiplied with b and stores in c)
c=
14 32 50
32 77 122
50 122 194
APPLICATION ORIENTATION IN ENGINEERING MATHEMATICS
AND MATHEMATICAL MODELING , SV NIT, SURAT Dec 26-30,2006.- 14
>> m = [ 2 1 5; 5 4 9;8 6 3];
>> n = inv(m) (Computes the inverse of the matrix a)
n=
1.1351 -0.7297 0.2973
-1.5405 0.9189 -0.1892
0.0541 0.1081 -0.0811
>> l = det(m) (Computes the determinant of a)
l=
-37
>> eig(a) (display eigen values of a)
ans =
16.1168
-1.1168
0.0000
>> [v,d]=eig(a) (gives eigen values and eigen vectors vof
a)
v=
0.2320 0.7858 0.4082
0.5253 0.0868 -0.8165
0.8187 -0.6123 0.4082
d=
16.1168 0 0
0 -1.1168 0
0 0 0.0000
>> size(a) (gives size of the matrix a)
ans =
3 3
>> rank(a) (Displays rank of a)
ans =
Creating vectors
The command
>> x = [1 2 3 4] (creates a row vector x)
>>y =x’ (transposes x to get a column vector y)
This can also be done by typing
APPLICATION ORIENTATION IN ENGINEERING MATHEMATICS
AND MATHEMATICAL MODELING , SV NIT, SURAT Dec 26-30,2006.- 15
>>y=[1;2;3;4]
The commands
>> t = 1:6 produces a row vector [1 2 3 4 5 6]
>>x = 1:2:6 produces the row vector x = [1 3 5]
The command x = p:r:q produces a row vector with entries starting from p and
subsequent entries are r more than the preveous values and maximum upto q. here p,q and r
need not be integer values.
The command
>> t = linspace(p,q,m)
creates a vector having m equi-spaced elements , beginning from p and ending with q.
Example
>> t = linspace(0,pi,20) ( produces 20 equi-spaced points from 0 till π ).
t=
Columns 1 through 7
0 0.17 0.33 0.50 0.66 0.83 0.99
Columns 8 through 14
1.16 1.32 1.49 1.65 1.82 1.98 2.15
Columns 15 through 20
2.31 2.48 2.65 2.81 2.98 3.14
Element-wise operations of matrices
The operations *, ^, \, / can be made to operate entry-wise by preceding them by a
period .
>> [ 1 2 3 4] .* [1 2 3 4] (element-wise product)
ans =
1 4 9 16
>> [1 2 3 4] .^ 2 (element-wise power)
ans =
1 4 9 16
APPLICATION ORIENTATION IN ENGINEERING MATHEMATICS
AND MATHEMATICAL MODELING , SV NIT, SURAT Dec 26-30,2006.- 16
>>a=magic(3) (creates a 3 by 3 magic matrix)
a=
8.00 1.00 6.00
3.00 5.00 7.00
4.00 9.00 2.00
>> b=a'
b=
8.00 3.00 4.00
1.00 5.00 9.00
6.00 7.00 2.00
>> a./b (dot right division)
ans =
1.00 0.33 1.50
3.00 1.00 0.78
0.67 1.29 1.00
>> a.\b (dot left division)
ans =
1.00 3.00 0.67
0.33 1.00 1.29
1.50 0.78 1.00
The following are some special matrices generated by built-in statements and functions
>> a = magic(4) (Produces Magic square of size 4)
a=
16 2 3 13
5 11 10 8
9 7 6 12
4 14 15 1
APPLICATION ORIENTATION IN ENGINEERING MATHEMATICS
AND MATHEMATICAL MODELING , SV NIT, SURAT Dec 26-30,2006.- 17
>> b = rand(5) (Generates Random matrix of size 5)
b=
0.9501 0.7621 0.6154 0.4057 0.0579
0.2311 0.4565 0.7919 0.9355 0.3529
0.6068 0.0185 0.9218 0.9169 0.8132
0.4860 0.8214 0.7382 0.4103 0.0099
0.8913 0.4447 0.1763 0.8936 0.1389
>> a = hilb(5)
a=
1.0000 0.5000 0.3333 0.2500 0.2000
0.5000 0.3333 0.2500 0.2000 0.1667
0.3333 0.2500 0.2000 0.1667 0.1429
0.2500 0.2000 0.1667 0.1429 0.1250
0.2000 0.1667 0.1429 0.1250 0.1111
is the Hilbert matrix, the king of ill-conditioned matrix of order 5.
>> ones(5) (generates square matrix of order 5 with all entries 1)
ans =
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
>> zeros(6) (generates matrix with all entries zero)
ans =
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
Matrix building functions
1. eye(n) - Identity matrix of order n
2. diag(a) - Vector consisting of diagonal of a
3. triu(a) - Upper triangular part of a
4. tril(a) - Lower triangular part of a
APPLICATION ORIENTATION IN ENGINEERING MATHEMATICS
AND MATHEMATICAL MODELING , SV NIT, SURAT Dec 26-30,2006.- 18
Data from External files
We can also load a matrix from an external ASCII file, say data.ext (where .ext is any
extension). If this ascii file contain a rectangular array of just the numeric matrix entries, then
to load the matrix type the command
>> data.ext
Submatrices and Colon Notation
Consider a matrix a give by
>> a = [1 2 3 4;5 6 7 1;2 3 4 5]
a=
1 2 3 4
5 6 7 1
2 3 4 5
>> b = a(:,3) (Vector consisting of 3rd column of a)
b=
3
7
4
>> c = a(3,:) (Third row of a)
c=
2 3 4 5
>> d=a(end,: )
d=
2 3 4 5
>> e= a(1:2,3) (Vector consisting of the first 2 entries of the 3rd column of a)
e=
3
7
>> d = a(1:2,:) (First two rows)
d=
1 2 3 4
5 6 7 1
APPLICATION ORIENTATION IN ENGINEERING MATHEMATICS
AND MATHEMATICAL MODELING , SV NIT, SURAT Dec 26-30,2006.- 19
>> f = a(:,[2 4]) (Columns 2 and 4)
f=
2 4
6 1
3 5
>> aa = a(1:2, 3:4) (Submatrix)
aa =
3 4
7 1
The matrix a(1:end,1:end) is same as the original matrix a.
Matrices can be built from blocks of matrices
>> a = [1 2 3;4 5 6;7 8 9]
>> b = [a, zeros(3,2); ones(2,3),eye(2)] ( will build a 5 by 5 matrix)
b=
1 2 3 0 0
4 5 6 0 0
7 8 9 0 0
1 1 1 1 0
1 1 1 0 1
Functions of vectors
>> x= [1:2:10] Makes a row vector t having element starting from 1 up to 10 with step
size 2)
x=
1 3 5 7 9
>> tt = [5:-1:0] (Here increment is –1)
tt =
5 4 3 2 1 0
APPLICATION ORIENTATION IN ENGINEERING MATHEMATICS
AND MATHEMATICAL MODELING , SV NIT, SURAT Dec 26-30,2006.- 20
>> t = 1:.2:2 (Here increment is not an integer)
t=
1.0000 1.2000 1.4000 1.6000 1.8000 2.0000
>> max(x) (maximum element in the vector t)
ans =
>> min(x) (minimum element in the vector t)
ans =
>> sum(x) (sum of all elements in the vector t)
ans =
25
>> mean(x) (mean of elements of t)
ans =
>>sort(x) (arrange in ascending order)
ans =
1 3 5 7 9
>> prod(x) (Product of elements)
ans =
945
>> median(x) (computes median)
ans =
>> any(t) (produces logical value 1 if any entry is non-zero)
ans =
>> all(x) (produces logical value 1 if all entries are non-zero)
APPLICATION ORIENTATION IN ENGINEERING MATHEMATICS
AND MATHEMATICAL MODELING , SV NIT, SURAT Dec 26-30,2006.- 21
ans =
>> std(x) (standard deviation)
ans =
3.1623
Functions of Matrices and Vectors
Function Task Function Task
inv Matrix inverse svds A few singular values
cond Condition number poly Characteristic
with respect to polynomial
inversion
condest 1-norm condition polyeig Polynomial
number estimate. eigenvalue problem
chol Cholesky condeig Condition number
factorization with respect to
eigenvalues
cholinc Incomplete Cholesky hess Hessenberg form
factorization
lu LU factorization qz QZ factorization for
generalized
eigenvalues
luinc Incomplete LU schur Schur decomposition
factorization
qr Orthogonal-triangular expm Matrix exponential
decomposition
nnls Non-negative least- logm Matrix logarithm
squares
pinv Pseudoinverse sqrtm Matrix square root
lscov Least squares with funm Evaluate general
known covariance matrix function
eig Eigenvalues and qrdelete Delete column from
eigenvectors QR factorization
svd Singular value qrinsert Insert column in QR
decomposition factorization
eigs A few eigenvalues rsf2csf Real block diagonal
form to complex
diagonal form
cdf2rdf Complex diagonal balance Diagonal scaling to
form to real block improve eigenvalue
diagonal form accuracy
APPLICATION ORIENTATION IN ENGINEERING MATHEMATICS
AND MATHEMATICAL MODELING , SV NIT, SURAT Dec 26-30,2006.- 22
Matrix functions can also be evaluated by the funm command.
f = funm(a,fun) evaluates the function fun at the square matrix a.
The MATLAB functions exp, log, cos, sin, cosh, sinh can be passed
as fun,
That is, funm(a,@exp), funm(a,@log), funm(a,@cos), funm(a,@sin),
funm(a,@cosh), funm(a,@sinh) are all allowed.
Example: >> a=magic(3)
a=
8 1 6
3 5 7
4 9 2
>> b=funm(a,@sin)
b=
-0.3850 1.0191 0.0162
0.6179 0.2168 -0.1844
0.4173 -0.5856 0.8185
>> c=sin(a)
c=
0.9894 0.8415 -0.2794
0.1411 -0.9589 0.6570
-0.7568 0.4121 0.9093
Note that sin(a) and matrix sine funm(a,@sin) are different.
For matrix square roots use sqrtm(a) instead. Remember sqrt and sqrtm are different.
aa=sqrtm(a)
aa =
2.7065 + 0.0601i 0.0185 + 0.5347i 1.1480 - 0.5948i
0.4703 + 0.0829i 2.0288 + 0.7378i 1.3739 - 0.8207i
0.6962 - 0.1430i 1.8257 - 1.2725i 1.3511 + 1.4155i
ab=sqrt(a)
ab =
2.8284 1.0000 2.4495
APPLICATION ORIENTATION IN ENGINEERING MATHEMATICS
AND MATHEMATICAL MODELING , SV NIT, SURAT Dec 26-30,2006.- 23
1.7321 2.2361 2.6458
2.0000 3.0000 1.4142
For matrix exponentials, either of expm(a) and funm(a,@exp) may be
the more accurate, depending on a.
>> d=expm(a)
d=
1.0e+006 *
1.0898 1.0896 1.0897
1.0896 1.0897 1.0897
1.0896 1.0897 1.0897
>> d1=funm(a,@exp)
d1 =
1.0e+006 *
1.0898 1.0896 1.0897
1.0896 1.0897 1.0897
1.0896 1.0897 1.0897
The function represented by fun must have a Taylor series with an
infinite radius of convergence.
4. Plotting Graphs
2-D plots :
Suppose we want to plot the graph of y = sin(x), in a interval [0,10]. Type as follows:
>> x = 0:0.5:10; (generates points in the given interval)
>> y = sin(x); (calculate function values at the x points)
>> plot(x, y) (Plots x verses y)
This will display the following graph:
APPLICATION ORIENTATION IN ENGINEERING MATHEMATICS
AND MATHEMATICAL MODELING , SV NIT, SURAT Dec 26-30,2006.- 24
1
0.8
0.6
0.4
0.2
-0.2
-0.4
-0.6
-0.8
-1
0 1 2 3 4 5 6 7 8 9 10
We can also give the title, x-label, y-label to the graph, to do this you type as follows on
MATLAB command prompt:
>> title(‘Graph Of Sine Function’);
>>xlabel(‘X Values’);
>>ylabel(‘Y=Sin(x)’);
It will display the graph as follows:
Graph Of Sine Function
1
0.8
0.6
0.4
0.2
Y= Sin(x)
-0.2
-0.4
-0.6
-0.8
-1
0 1 2 3 4 5 6 7 8 9 10
X Values
More on plots
• plot(x,y) plots vector y versus vector x. If x or y is a matrix, then the vector is plotted
versus the rows or columns of the matrix, whichever line up.
• plot(y) plots the columns of y versus their index.
• If y is complex, plot(y) is equivalent to plot(real(y),imag(y)).
In all other uses of plot, the imaginary part is ignored.
• various line types, plot symbols and colors may be obtained with
>> plot(x,y,s)
where s is a character string made from one element from any or all the following columns:
APPLICATION ORIENTATION IN ENGINEERING MATHEMATICS
AND MATHEMATICAL MODELING , SV NIT, SURAT Dec 26-30,2006.- 25
y yellow . point - solid m magenta
o circle : dotted c cyan x x-mark
-. dashdot r red + plus -- dashed
g green * star b blue s square
w white d diamond k black v triangle (down)
^ triangle (up) < triangle (left) > triangle (right) p pentagram
h hexagram
Example:
plot(x,y,'c+:') plots a cyan dotted line with a plus at each data point.
plot(x,y,'bd') plots blue diamond at each data point but does not draw any line.
More than one plot in the same graph
There are mainly three ways to generate overlay plots.
(i) By using the following plot command
plot(x1,y1,s1,x2,y2,s2,x3,y3,s3,...)
This combines the plots defined by the (x,y,s) triples, where the x's and y's are vectors or
matrices and the s's are strings.
>> plot(x, y, ‘b’, x, z, ‘g’)
puts two plots, plot(x, y, ‘b’) and plot(x, z, ‘g’) in one graph. The first one with blue color
and the second with green color.
>> plot(x, y, 'y-', x, y, 'go')
plots the data twice, with a solid yellow line interpolating green circles at the data points.
Example:
>> t = linspace(0,2*pi); (line space generates 100 t points between 0 and 2π )
>> x = sin(t);
>> y = cos(t);
>> plot(t, x,’*’, t, y,’-’) (plots sine and cos graphs in the same plot)
>> legend(‘x = sin(t)’, ’y = cos(t)’) (provides legends for graphs)
>> grid (provides grid lines)
APPLICATION ORIENTATION IN ENGINEERING MATHEMATICS
AND MATHEMATICAL MODELING , SV NIT, SURAT Dec 26-30,2006.- 26
1
x=sin(t)
0.8 y=cos(t)
0.6
0.4
0.2
-0.2
-0.4
-0.6
-0.8
-1
0 1 2 3 4 5 6 7
(ii) Using hold command. The following command gives the same graph as above.
>> t = linspace(0,2*pi);
>> x = sin(t);
>> y = cos(t);
>> plot(t, x,’*’)
>> legend(‘x = sin(t)’)
>>hold on (holds this graph for the next plot also)
>>plot( t, y,’-’)
>> legend(’y = cos(t)’)
>> grid
(iii) The line command . The line command is a low-level graphics command used by
the plot command to generate lines.
For example, to plot f ( x) = x 2 and g ( x ) = x from 0 to 2.
>> x=linspace(0,2,50);
>> f=x.^2;
>> g=sqrt(x);
>> plot(x,f)
>> line(x,g,’o’)
>> xlabel('x')
>> ylabel('functions')
>> title('two functions using line command')
>> legend('x^2','sqrt(x)')
The graph is shown below.
APPLICATION ORIENTATION IN ENGINEERING MATHEMATICS
AND MATHEMATICAL MODELING , SV NIT, SURAT Dec 26-30,2006.- 27
If you want to give range to x -axis from xmin to xmax and to choose y-axis between ymin
and ymax, then enter the following command after the plot command :
>> axis([xmin xmax ymin ymax])
The command
>>axis([xmin xmax] [ymin ymax])
will also do the same. The commands
>> axis([0 pi –inf inf])
is also valid, where inf stands for infinity.
This command can be used to zoom a graph in a desired domain.
See for example, the plot shown above can be zoomed in the domain [0 1] x [0 1] by adding
the command
>>axis([0 1 0 1])
at the end of the group of commands shown above. We get the following graph:
APPLICATION ORIENTATION IN ENGINEERING MATHEMATICS
AND MATHEMATICAL MODELING , SV NIT, SURAT Dec 26-30,2006.- 28
The commands
>> axis(‘equal’) will scale x and y axes equal.
>> axis(‘square’) sets default rectangular frame to a square.
>> axis(‘normal’) sets the default rectangular frame.
>> axis(‘off’) removes the surrounding frame and the tick marks.
Subplots
You can hold more than one set of axes on one figure window. The command
subplot(m,n,p) subdivides the current figure window into an m-by-n matrix of plotting
areas and chooses the pth area to be active.
Example:
>> x = -2*pi:pi/10:2*pi;
>> y = x.^2;
>> z = sin(x);
>> y1 = cos(x);
>> z1 = exp(x);
>> subplot(2,2,1),plot(x,y)
>> grid
>> subplot(2,2,2),plot(x,z)
>> grid
>> subplot(2,2,3),plot(x,y1)
>> grid
>> subplot(2,2,4),plot(x,z1)
>>grid
It displays the graph as follows:
40 1
35
30 0.5
25
20 0
15
10 -0.5
0 -1
-10 -5 0 5 10 -10 -5 0 5 10
1 600
500
0.5
400
0 300
200
-0.5
100
-1 0
-10 -5 0 5 10 -10 -5 0 5 10
APPLICATION ORIENTATION IN ENGINEERING MATHEMATICS
AND MATHEMATICAL MODELING , SV NIT, SURAT Dec 26-30,2006.- 29
For each subplot, label, legends etc can be added as required.
Functions for 2-D plots
Function Task Function Task
plot Linear plot hold Hold current graph
loglog Log-log scale plot axes Create axes in
arbitrary positions
semilogx Semi-log scale plot subplot Create axes in tiled
with log scale on x- positions
axis.
semilogy Semi-log scale plot legend Graph legend
with log scale on y-
axis.
polar Polar coordinate plot title Graph title
plotyy Graphs with y tick xlabel X-axis label
labels on the left and
right
axis Control axis scaling ylabel Y-axis label
and appearance
zoom Zoom in and out on a text Text annotation
2-D plot
grid Grid lines gtext Place text with
mouse
bar Creates a bar graph area Filled area plot
barh Horizontal bar graph comet Makes an animated
2-D plot
compass Arrow graph for contour Contour plot
comples numbers
contourf Filled Contour plot fill Draws filled
polygons
fplot Plots function of a hist Plots histogram
single function
pie Creates pie chart plotmatrix Creates a scatter plot
of matrixd
scatter Plots scatter diagram quiver Plots a vector field
box Axis box
Examples of some plots:
1. fplot : function f ( x) = e − x x 3 cos( x) [0,10π ]
>>fplot('exp(-x)*x^3*cos(x)',[0,10*pi]) produces the following graph.
APPLICATION ORIENTATION IN ENGINEERING MATHEMATICS
AND MATHEMATICAL MODELING , SV NIT, SURAT Dec 26-30,2006.- 30
2. polar : function r =2cos2t, 0 ≤ t ≤ 2π
t=linspace(0,2*pi,200);
r=abs(2*cos(2*t));
polar(t,r)
3. fill : function r =2cos2t, 0 ≤ t ≤ 2π
t=linspace(0,2*pi,200);
r=abs(2*cos(2*t));
x=r.*cos(t);
y=r.*sin(t);
fill(x,y,'k')
APPLICATION ORIENTATION IN ENGINEERING MATHEMATICS
AND MATHEMATICAL MODELING , SV NIT, SURAT Dec 26-30,2006.- 31
4. bar function r =2cos2t, 0 ≤ t ≤ 2π
t=linspace(0,2*pi,200);
r=abs(2*cos(2*t));
y=r.*sin(t);
bar(t,y)
axis([0 pi,0 inf])
5. area : function f(x) = xsin(x) 0 ≤ t ≤ 10π
t=linspace(0,10*pi,200);
x=t.*sin(t);
area(t,x)
APPLICATION ORIENTATION IN ENGINEERING MATHEMATICS
AND MATHEMATICAL MODELING , SV NIT, SURAT Dec 26-30,2006.- 32
6. stem : function f(x) = xsin(x) 0 ≤ t ≤ 2π
t=linspace(0,10*pi,200);
x=t.*sin(t);
stem(t,x)
7. hist : histogram of 50 randomly distributed numbers.
x=rand(50,1);
hist(x)
APPLICATION ORIENTATION IN ENGINEERING MATHEMATICS
AND MATHEMATICAL MODELING , SV NIT, SURAT Dec 26-30,2006.- 33
8. pie The following codes shows how to get a pie chart
item=char('food','savings','housing','education')
expense=[40 10 20 30];
pie(expense)
for i =1:4
gtext(item(i,:));
end
title('pie chart for expenditure')
3-D plots
Similar to 2-D plots, plot3 produces curves in 3-dimentional space
>> plot3(x,y,z)
APPLICATION ORIENTATION IN ENGINEERING MATHEMATICS
AND MATHEMATICAL MODELING , SV NIT, SURAT Dec 26-30,2006.- 34
produces the plot of the piecewise linear curves in 3-D space passing through the coordinates
of the respective elements of x, y and z.
Example
>> t :-20*pi:0.01:20*pi;
>> x = cos(t);
>> y = sin(t);
>> z = t.^3;
>> plot3(x, y, z)
will produce a helix which is compressed near the x-y plane:
5
x 10
2.5
1.5
0.5
-0.5
-1
-1.5
-2
-2.5
1
0.5 1
0.8
0.6
0 0.4
0.2
0
-0.2
-0.5 -0.4
-0.6
-0.8
-1 -1
We can also give the title, x-label, y-label, z-label, grid to the 3-D graphs as we are
doing in 2-D graphs. It is possible to rotate the 3D graphs by clicking on the rotate 3D button
in the toolbar of the figure window. Rotation and different views are possible with rotate3d
and view commands.
3D Mesh Plots
Using mesh command we can draw 3-dimensional wire mesh surface.
>> mesh(z)
creates a 3-dimentional plot of the elements of the matrix z. The mesh surface is defined by
the z-co-ordinates. You can plot mesh surface by the z-co-ordinates of points above a
rectangular grid in the x-y plane. It forms the mesh plot by joining adjacent points with
straight lines.
APPLICATION ORIENTATION IN ENGINEERING MATHEMATICS
AND MATHEMATICAL MODELING , SV NIT, SURAT Dec 26-30,2006.- 35
Example 1:
>> xx = linspace(-2,2,200);
>> yy = xx;
>> [x, y] = meshgrid(xx,yy);
>> z = x.^2+y.^2;
>> mesh (z)
The graph is as follows:
>> [x,y] = meshgrid(-2:.2:2,-2:.2:2); can be used to replace the first 3 lines given in the
above example.
Example 2:
>> [x,y,z] = peaks(200); (peaks is a built-in function in MATLAB)
>> mesh (z);
>> xlabel(‘X-axis’);
>> ylabel(‘Y-axis’);
>> zlabel(‘Z-axis’);
>> title(‘Mesh plots of Peaks’);
It will display the graph as follows:
APPLICATION ORIENTATION IN ENGINEERING MATHEMATICS
AND MATHEMATICAL MODELING , SV NIT, SURAT Dec 26-30,2006.- 36
Mesh plots and Contours plots
Instead of mesh(z), if we use meshc(z) we get mesh plot and contour of the 3D graph as is
shown below:
3D contour plots
The following figures shows the mesh and 3D contours of the function
5
z=
1+ x + y2
2
x=linspace(-3,3,50);
y=x;
[x,y]=meshgrid(x,y);
z=5./(1+x.^2+y.^2);
mesh(z)
figure(2)
contour3(z)
title('Mesh plot of Peaks')
xlabel('X-axis')
ylabel('Y-axis')
zlabel('Z-axis')
APPLICATION ORIENTATION IN ENGINEERING MATHEMATICS
AND MATHEMATICAL MODELING , SV NIT, SURAT Dec 26-30,2006.- 37
Surface plots
Surface plots look like a mesh plot, the only difference is that the spaces between the lines
are filled in. Surface plots are generated by using surf function. We plot the above graph
using surf
>> [x,y,z] = peaks(20);
>> surf (x,y,z);
>> xlabel(‘X-axis’);
>> ylabel(‘Y-axis’);
>> zlabel(‘Z-axis’);
>> title(‘Surface plots of Peaks’);
The graph is as follows
As in the case of meshc, surfc(z) provides the surface along with contour.
APPLICATION ORIENTATION IN ENGINEERING MATHEMATICS
AND MATHEMATICAL MODELING , SV NIT, SURAT Dec 26-30,2006.- 38
Functions for 3-D plots
Function Task Function Task
plot3 Plot lines and points mesh 3-D mesh surface
in 3-D space
surf 3-D colored surface fill3 Filled 3-D polygons
colormap Color look-up table caxis Pseudocolor axis
scaling
shading Color shading mode hidden Mesh hidden line
removal mode
brighten Brighten or darken surfl 3-D shaded surface
color map with lighting
lighting Lighting mode material Material reflectance
mode
specular Specular reflectance diffuse Diffuse reflectance
surfnorm Surface normals hsv Hue-saturation-value
color map
hot Black-red-yellow- gray Linear gray-scale
white color map color map
bone Gray-scale with tinge copper Linear copper-tone
of blue color map color map
pink Pastel shades of pink white All white color map
color map
flag Alternating red, lines Color map with the
white, blue, and line colors
black color map
colorcube Enhanced color-cube jet Variant of HSV
color map
prism Prism color map cool Shades of cyan and
magenta color map
autumn Shades of red and spring Shades of magenta
yellow color map and yellow color map
winter Shades of blue and summer Shades of green and
green color map yellow color map
axis Control axis scaling zoom Zoom in and out on a
and appearance 2-D plot
grid Grid lines box Axis box
hold Hold current graph axes Create axes in
arbitrary positions
subplot Create axes in tiled view 3-D graph viewpoint
positions specification
viewmtx View transformation rotate3d Interactively rotate
matrix view of 3-D plot
title Graph title xlabel X-axis label
ylabel Y-axis label zlabel Z-axis label
colorbar Display color bar text Text annotation
(color scale)
gtext Mouse placement of text
APPLICATION ORIENTATION IN ENGINEERING MATHEMATICS
AND MATHEMATICAL MODELING , SV NIT, SURAT Dec 26-30,2006.- 39
MATLAB Programming
We can also do programming in MATLAB as we are doing in FORTRAN, C & C++. To
make a file in MATLAB we have to click on “New” in the file menu in menu bar. It will
open a new file as we are doing in “word”; and if we save this file (called m-file), will be
saved in “bin” folder or “work” folder of MATLAB.
Such files are called “M-files” because they have an extension of “.m” in its filename. Much
of your work with MATLAB will be creating and refining M-files.
There are two types of M-files: Script Files and Function Files
Script Files
A script file consists of a sequence of normal MATLAB statements. If the file has the
filename, say, rkg.m, then the MATLAB command
>> rkg
will cause the statements in the file to be executed. Variables in a script file are global and
will change the value of variables of the same name in the environment of the current
MATLAB session.
Script files are often used to enter data into a large matrix; in such a file, entry errors
can be easily edited out.
Example: In a file rkg.m enter the following:
% This is a sample m-file
a = [1,2,3;0,1,1;1,2,3]
b =a’;
c = a+b
d = inv(c)
save this file. Then to execute this file, type
>> rkg <ENTER> We get the following output:
a=
1 2 3
0 1 1
1 2 3
b=
1 0 1
2 1 2
3 1 3
APPLICATION ORIENTATION IN ENGINEERING MATHEMATICS
AND MATHEMATICAL MODELING , SV NIT, SURAT Dec 26-30,2006.- 40
c=
2 2 4
2 2 3
4 3 6
d=
-1.5000 0 1.0000
0 2.0000 -1.0000
1.0000 -1.0000 0
The % symbol indicates that the rest of the line are comment text. MATLAB will ignore the
rest of the line. However, the first comment lines which document the m-file are available to
the on-line help facility and will be displayed.
An M-file can also reference other M-files, including referencing itself recursively.
Function Files
Function files provide extendibility to MATLAB. You can create new functions
specific to your problem which will then have the same status as other MATLAB functions.
Variables in a function file are by default local. However, you can declare a variable to be
global if you wish.
Example
function y = prod (a,b)
y = a*b;
Save this file with filename prod.m then type at the MATLAB prompt
>> prod (3,4)
ans =
12
User Input to a program
In MATLAB to get input from user the syntax rule is :
variable name = input (‘variable’);
As we know that if we don’t write “;” after a statement in MATLAB, it will print the
output also. That means if in a programme we write:
a=input (‘ Enter a number ‘)
And on command prompt if we run this program it will be displayed like:
Enter a number
APPLICATION ORIENTATION IN ENGINEERING MATHEMATICS
AND MATHEMATICAL MODELING , SV NIT, SURAT Dec 26-30,2006.- 41
If we type 2 at the cursor then we get the output as
a=
2
Control Flow
MATLAB offers the following decision making or control flow structures:
1. If- Else –End Construction
2. For loops
3. While loops
4. Switch-Case constructions etc.
SYNTAX RULE FOR CONTROLLING THE FLOW:
1) if statement condition:
The general form of the if statement is:
if expression
statements
elseif expression
statements
else
statements
end
The statements are executed if the real part of the expression has all non-zero elements.
The else and elseif parts are optional. zero or more elseif parts can be used as well as nested
if's. The expression is usually of the form
expr rop expr
where rop is ==, <, >, <=, >=, or ~=.
Example:
if i == j
a(i,j) = 2;
elseif abs(i-j) == 1
a(i,j) = -1;
else
2) else used with if:
else is used with if. The statements after the else are executed if all the preceeding if and
elseif expressions are false.
The general form of the if statement is:
if expression
statements
elseif expression
statements
else
APPLICATION ORIENTATION IN ENGINEERING MATHEMATICS
AND MATHEMATICAL MODELING , SV NIT, SURAT Dec 26-30,2006.- 42
statements
end
3) elseif if statement condition:
elseif is used with if. The statements after the elseif are executed if the expression is true
and all the preceeding if and elseif expressions are false. An expression is considered true if
the real part has all non-zero elements. elseif does not need a matching end, while else if
does.
the general form of the if statement is:
if expression
statements
elseif expression
statements
else
statements
end
4) end terminate scope of for, while, switch, try, and if statements. Without end's, for, while,
switch, try, and if wait for further input. each end is paired with the closest previous unpaired
for, while, switch, try or if and serves to terminate its scope. end can also serve as the last
index in an indexing expression. in that context,
end = size(x,k) when used as part of the k-th index. examples of this use are, x(3:end) and
x(1,1:2:end-1). when using end to grow an array, as in x(end+1) = 5, make sure x exists first.
5) for repeat statements a specific number of times:
The general form of a for statement is:
for variable = expr, statement, ..., statement
end
The columns of the expression are stored one at a time in the variable and then the
following statements, up to the
end, are executed. The expression is often of the form x:y, in which case its columns are
simply scalars. some examples
Example: (assume n has already been assigned a value)
for i = 1:n,
for j = 1:n,
a(i,j) = 1/(i+j-1);
end
end
for s = 1.0: -0.1: 0.0, end steps s with increments of -0.1
for e = eye(n), ... end sets e to the unit n-vectors.
Long loops are more memory efficient when the colon expression appears in the for
statement since the index vector is never created.
APPLICATION ORIENTATION IN ENGINEERING MATHEMATICS
AND MATHEMATICAL MODELING , SV NIT, SURAT Dec 26-30,2006.- 43
6) The break statement can be used to terminate the loop prematurely. break terminate
execution of while or for loop. In nested loops, break exits from the innermost loop only.
7) while repeat statements an indefinite number of times.
The general form of a while statement is:
while expression
statements
end
The statements are executed while the real part of the expression has all non-zero elements.
The expression is usually the result of expr rop expr where rop is ==, <, >, <=, >=, or ~=.
Example:
(assuming a already defined)
e = 0*a; f = e + eye(size(e)); n = 1;
while norm(e+f-e,1) > 0,
e = e + f;
f = a*f/n;
n = n + 1;
end
8) switch switches among several cases based on expression:
the general form of the switch statement is:
switch switch_expr
case case_expr,
statement, ..., statement
case {case_expr1, case_expr2, case_expr3,...}
statement, ..., statement
...
otherwise,
statement, ..., statement
end
The first case where the switch_expr matches the case_expr is executed. when the case
expression is a cell array (as in the second case above), the case_expr matches if any of the
elements of the cell array match the switch expression. If none of the case expressions match
the switch expression then the otherwise case is executed (if it exists). Only one case is
executed and execution resumes with the statement after the end. the switch_expr can be a
scalar or a string. A scalar switch_expr matches a case_expr if switch_expr==case_expr. A
string switch_expr matches a case_expr if strcmp(switch_expr,case_expr) returns 1 (true).
Example:
(assuming method exists as a string variable):
switch lower(method)
case {'linear','bilinear'}, disp('method is linear')
APPLICATION ORIENTATION IN ENGINEERING MATHEMATICS
AND MATHEMATICAL MODELING , SV NIT, SURAT Dec 26-30,2006.- 44
case 'cubic', disp('method is cubic')
case 'nearest', disp('method is nearest')
otherwise, disp('unknown method.')
end
9) case switch statement case:
case is part of the switch statement syntax, whose general form is:
switch switch_expr
case case_expr,
statement, ..., statement
case {case_expr1, case_expr2, case_expr3,...}
statement, ..., statement
...
otherwise,
statement, ..., statement
end
10) otherwise default switch statement case.
otherwise is part of the switch statement syntax, whose general form is:
switch switch_expr
case case_expr,
statement, ..., statement
case {case_expr1, case_expr2, case_expr3,...}
statement, ..., statement
...
otherwise,
statement, ..., statement
end
The otherwise part is executed only if none of the preceeding case expressions match the
switch expression.
11) try begin try block:
The general form of a try statement is:
try, statement, ..., statement, catch, statement, ..., statement end
Normally, only the statements between the try and catch are executed. however, if an error
occurs while executing any of the statements, the error is captured into lasterr and the
statements between the catch and end are executed. if an error occurs within the catch
APPLICATION ORIENTATION IN ENGINEERING MATHEMATICS
AND MATHEMATICAL MODELING , SV NIT, SURAT Dec 26-30,2006.- 45
statements, execution will stop unless caught by another try...catch block. The error string
produced by a failed try block can be obtained with lasterr.
12) catch begin catch block:
The general form of a try statement is:
try statement, ..., statement, catch statement, ..., statement end
13) return returns to invoking function:
return causes a return to the invoking function or to the keyboard.
it also terminates the keyboard mode.
normally functions return when the end of the function is reached.
a return statement can be used to force an early return.
Example:
function d = det(a)
if isempty(a)
d = 1;
return
else
...
end
How to run a program in MATLAB?
Suppose we have created a m-file & saved. Now to run this program, on command prompt
type the file name and just press the ENTER KEY that will run the file.
Data File:
Now to make a data file in MATLAB, we just make a file in which all the data are stored.
Now we make another file in which the operation on that data is to be done. Then in this file,
where we have to call that data we have to just type the file name of the file in which data is
stored and write the rest of the programming statements. So when run this file the file in
which data is stored will be called and then rest of the programming statements are executed
& finally we get the output.
MEX-Files:
We can call our C programs from MATLAB as if they were built in functions. Those
programs in C which are callable in MATLAB are referred as MEX-Files. MEX-files are
dynamically linked subroutines that the MATLAB interpreter can automatically load &
execute. For example the following program in C to add two integers having file name “add”.
APPLICATION ORIENTATION IN ENGINEERING MATHEMATICS
AND MATHEMATICAL MODELING , SV NIT, SURAT Dec 26-30,2006.- 46
#include<stdio.h>
main( )
{ int a=2,b=3;
d=a+b;
printf(‘sum is:’,d);
return 0;
}
To compile & link this example at the MATLAB prompt, type
>>mex add.c
and press the “ENTER”key, it will give the output.
Some useful commands for programming:
>> echo on --- Echoing of commands in all script files
>> echo off --- Turns off echo
>> echo on all --- turns on of command including function files
>> disp(‘Any string’) --- Displays the string
>> diary file --- Causes copy of all subsequent keyboard input and most
of the resulting output (but not graphs) to be written on
the named file.
>> pause --- causes to stop execution of until any key is pressed.
Some Examples:
1) Example for if, else
for i = 1:n
for j = 1:n
if i==j
a(i, j) = 2
elseif abs(i – j) ==1
a(i, j) = -1;
else
a(i, j) = 0;
end
end
end
2) Example for while
eps = 1
while (1+eps)>1
eps = eps/2;
end
eps = eps*2
3) Gauss Elimination Method
function [x] = gausselim(A,b)
APPLICATION ORIENTATION IN ENGINEERING MATHEMATICS
AND MATHEMATICAL MODELING , SV NIT, SURAT Dec 26-30,2006.- 47
% This subroutine will perform Gaussian elimination on the matrix you pass and solve
% the system AX = b
N = max(size(A))
for j = 2:N
for i = j:N
m = A(j,j-1) / A(j-1,j-1);
A(i, :) = A(i, :) – A(j-1,:)*m;
b(i) = b(i) – m*b(j-1);
end
end
%Perform back substitution
x = zeros(N, 1)
x(N) = b(N) / A(N, N)
for j = N-1:-1:1
x(j) = (b(j)-A(j,j+1:N)) / A(j, j)
end
RELATIONAL OPERATORS
MATLAB relational operators includes the following:
Relational Description
Operator
< Less than
<= Less than or equal to
> Greater than
>= Greater than or equal to
== Equal to
~= Not equal to
MATLAB relational operators can be used to compare two arrays of the same size, or
to compare an array to a scalar. When we compare an array to a scalar, scalar expansion is
used to compare the scalar to each array element and the result has the same size as the array.
NOTE: = and == mean two different things:
== compares two variables and returns ones where they are equal and zeros where they
are not; while, = is used to assign the output of an operation to a variables.
Example:
>> a = 1:0.5:10;
>> b = 5:0.5:14;
>> c = a > 5
c=
Columns 1 through 12
APPLICATION ORIENTATION IN ENGINEERING MATHEMATICS
AND MATHEMATICAL MODELING , SV NIT, SURAT Dec 26-30,2006.- 48
0 0 0 0 0 0 0 0 0 1 1 1
Columns 13 through 19
1 1 1 1 1 1 1
>> d = (a ==b)
d=
Columns 1 through 12
0 0 0 0 0 0 0 0 0 0 0 0
Columns 13 through 19
0 0 0 0 0 0 0
LOGICAL OPERATORS
MATLAB logical operators include the following:
Logical Operator Description
& AND
| OR
~ NOT
Example:
>> a = 1:15;
>> b = ~ ( a < 5 )
b=
Columns 1 through 12
0 0 0 0 1 1 1 1 1 1 1 1
Columns 13 through 15
1 1 1
>> c = ( a > 2 ) & (a < 8 )
c=
Columns 1 through 12
0 0 1 1 1 1 1 0 0 0 0 0
Columns 13 through 15
APPLICATION ORIENTATION IN ENGINEERING MATHEMATICS
AND MATHEMATICAL MODELING , SV NIT, SURAT Dec 26-30,2006.- 49
0 0 0
>> d = ( a > 2 ) | ( a < 8 )
d=
Columns 1 through 12
1 1 1 1 1 1 1 1 1 1 1 1
Columns 13 through 15
1 1 1
RULES FOR CONSTRUCTING M-FILES
Function M-files must satisfy a number of criteria. Some of them are as follows:
1. The function M-file name and the function name ( e.g., rkg) that appears in the first
line of the file should be identical. In reality, MATLAB ignores the function name in
the first line and executes functions based on the file name stored on disk.
2. Function M-file names can have up to 31 characters. This maximum may be limited
by the operating system, in which case the lower limit applies. MATLAB ignores
characters beyond the thirty-first or the operating system limit, so longer names can
be used, provided the legal characters point to a unique file name.
3. Function names must begin with a letter. Any combination of letters, numbers, and
underscores can appear after the first character. This naming rule is identical to that
for variables.
4. The first line of a function M-file is called the function declaration line and must
contain the word function followed by the calling syntax for the function in its most
general form. The input and output variables identified in the first line are variables
local to the function. The input variables contain data passed to the function and the
output variables contain data passed back from the function. It is not possible to pass
data back though the input variables.
5. The first sets of contiguous comment lines after the function declaration line are the
help text for the function. The first comment line is called the H1 line and is the line
searched by the lookfor command. The H1 line typically contains the function name
in uppercase characters and a concise description of the function’s purpose. Comment
lines after the first describe possible calling syntaxes, algorithms used, and simple
examples, if appropriate.
6. All statements after the first set of contiguous comment lines compose the body of the
function. The body of a function contains MATLAB statements that operate on the
input arguments and produce results in the output arguments.
7. A function M-file terminates after the last line in the file is executed or whenever a
return statement is encountered.
8. A function can abort operation and return control to the command window by calling
the function error. This function is useful for flagging improper function usage, as
shown in the following file fragment:
APPLICATION ORIENTATION IN ENGINEERING MATHEMATICS
AND MATHEMATICAL MODELING , SV NIT, SURAT Dec 26-30,2006.- 50
if length ( mat ) > 1
error ( ‘MAT must be a scalar.’)
end
if the function error is executed as shown, the string ‘VAL must be a scalar.’ Is
displayed in the command window after a line identifying the file the error message
originated from. If the function error is given a zero-length character string, it takes
no action.
9. A function can report a warning and then continue operation by calling the function
warning. This function is useful for reporting exceptions and other anomalous
behavior. warning (‘some message’) displays a character string in the command
window. The difference between the function warning and the function disp is that
warning messages can be turned on or off globally by issuing the commands warning
on and warning off, respectively.
10. Function M-files can contain calls to script files. When a script file is encountered, it
is evaluated in the function’s workspace, not the MATLAB workspace.
11. Multiple functions can appear in a single function M-file. Additional functions, called
subfunctions or local functions, are simply appended to the end of the primary
function. Subfunctions begin with a standard function statement line and follow
function construction rules.
12. Subfunctions can be called by the primary function in the M-file as well as by other
subfunctions in the same M-file. As with all functions, subfunctions have their own
individual workspaces.
13. Subfunctions can appear in any order after the primary function in a M-file. Help text
for subfunctions is not returned by the help command.
14. It is suggested that subfunction names begin with the word local (e.g., local_bsr).
Doing so improves the readability of the primary function because calls to local
functions are clearly identifiable. All local function names can have up to 31
characters.
15. In addition to subfunctions, M-files can call private M-files, which are standard
function M-files that reside in a subdirectory of the calling function that is entitled
private. Only functions in the immediate parent directory of private M-files have
access to private M-file.
16. It is suggested that private M-file names begin with the word private (e.g.,
private_bsr). Doing so improve the readability of the primary function because calls
to private functions are clearly identifiable. As with other function names, all private
M-file names can have up to 31 characters.
INPUT AND OUTPUT ARGUMENTS
MATLAB functions can have any number of input and output arguments. The features and
criteria of these arguments are as follows:
1. Function M-files can have zero input and zero output arguments.
2. Functions can be called with fewer input and output arguments than the function
definition line in the M-file specifies. Functions cannot be called with more input or
output arguments than the M-file specifies.
APPLICATION ORIENTATION IN ENGINEERING MATHEMATICS
AND MATHEMATICAL MODELING , SV NIT, SURAT Dec 26-30,2006.- 51
3. The number of input and output arguments used in a function call can be determined
by calls to the functions nargin and nargout, respectively. Since nargin and nargout
are functions, not variables, one cannot reassign them with statements such as
Nargin = nargin – 1
4. When a function is called, the input variables are not copied into the function’s
workspace, but their values are made readable within the function. However, if any
values in the input variables are changed, the array is then copied into the function’s
workspace. Thus, to conserve memory and increase speed, it is best to extract
elements from large arrays and then modify them, rather than forcing the entire array
to be copied into the function’s workspace. Note that using the same variable name
for both an input and output argument causes an immediate copying of the contents of
the variable into the function’s workspace. For example,
function y = myfunction (x, y, z)
causes the variable y to be copied immediately into the workspace of myfunction.
5. If a function declares one or more output arguments, but no output is desired, simply
do not assign values to the output variable or variables.
6. Functions can accept a variable and unlimited number of input arguments by
specifying varargin as the last input argument in the function declaration line.
Varargin is a predefined cell array whose ith cell is the ith argument starting from
where varargin appears. For example, consider a function having the function
declaration line
Function a = myfunction(varargin)
If this function is called as a = myfunction(x, y, z), then inside the function
varargin(1) contains the array x, varargin(2) contains the array y, and varargin(3)
contains the array z. Likewise, if the function is called as a = myfunction(x),
varargin has length 1 and
varargin{1} = x. Every time myfunction is called, it can be called with a different
number of arguments. In any case, the function nargin returns the actual number of
input arguments used.
In those cases where one or more input arguments are fixed, varargin must
appear as the last argument, such as
Function a = myfunction (x, y, varargin)
If this function is called as a = myfunction(x, y, z), then inside the function x and y
are available and varargin(1) contains z.
7. Functions can accept a variable and unlimited number of output arguments by
specifying varargout as the last output argument in the function declaration line.
Varargout is a predefined cell array whose ith cell is the ith argument starting from
where varargout appears. For example, consider a function having the function
declaration line
function varargout = myfunction (x)
If this function is called as [a, b] = function (x), then inside the function the contents
of varargout(1) must be assigned to the data that become the variable a, and
APPLICATION ORIENTATION IN ENGINEERING MATHEMATICS
AND MATHEMATICAL MODELING , SV NIT, SURAT Dec 26-30,2006.- 52
varargout(2) must be assigned to the data that become the variable b. As with
varargin, the length of varargout is equal to the number of output arguments used
and nargout returns this length. In those cases where one or more output arguments
are fixed, varargout must appear as the last argument in the function declaration line
–for example, function [a, b, varargout] = myfunction (x).
FUNCTION WORKSPACES
Functions accept inputs, act on those inputs, and create outputs. Any and all variables created
within the function are hidden from the MATLAB or base workspace. Each function has its
own temporary workspace that is created with each function call and then deleted when the
function completes execution. MATLAB functions can be called recursively and each call
has a separate workspace. In addition to input and output arguments, MATLAB provides
several techniques for communicating among function workspaces and the MATLAB or base
workspace.
1. Function can share variables with other function, the MATLAB workspace, and
recursive calls to themselves if the variables are declared global. To gain access to a
global variable within a function or the MATLAB workspace, the variable must be
declared global within each desired workspace. The MATLAB functions tic and toc
illustrate the use of global variables. The functions tic and toc form a simple
stopwatch for timing MATLAB operations. When tic is called, it declares the variable
TICTOC global, assigns the current time to it, and then terminates. Later when toc is
called, TICTOC is declared global in the toc workspace, there by providing access to
its contents, and the elapsed time is computed. It is important to note that the variable
TICTOC exists only in the workspaces of the functions tic and toc; it does not exist
in the MATLAB workspace unless global TICTOC is issued there.
2. In addition to sharing data through global variables, MATLAB provides the function
evalin, which allows one to reach into another workspace, evaluate an expression, and
return the result to the current workspace. The function evalin is similar to eval,
except that the string is evaluated in either the caller or base workspace. The caller
workspace is the workspace from which the current function was called. The base
workspace is the MATLAB workspace in the command window. For example,
A = evalin(‘caller’,’expression’) evaluates ‘expression’ in the caller workspace and
returns the results to the variable A in the current workspace. evalin also provides
error trapping with the syntax evalin(‘workspace’,’try’,’catch’), where ‘workspace’
is either ‘caller’ or ‘base’, ‘try’ is the first expression evaluated, and ‘catch’ is an
expression that is evaluated in the current workspace if the evaluation of ‘try’
produces an error.
3. Since one can evaluate an expression in another workspace, it makes sense that one
can also assign the results of some expression in the current workspace to a variable
in another workspace. The function assignin provides this capability.
assignin(‘workspace’,’vname’,X), where ‘workspace’ is either ‘caller’ or ‘base’,
assigns the contents of the variable X in the current workspace to a variable in the
‘caller’ or ‘base’ workspace named ‘vname’.
4. The function inputname provides a way to determine the variable names used when a
function is called. For example, suppose a function is called as
APPLICATION ORIENTATION IN ENGINEERING MATHEMATICS
AND MATHEMATICAL MODELING , SV NIT, SURAT Dec 26-30,2006.- 53
>> y = myfunction(xdot,time,sqrt(2))
issuing inputname(1) inside of myfunction returns the character string ‘xdot’,
inputname(2) returns ‘time’, and inputname (3) returns an empty array because
sqrt(2) is not a variable, but rather an expression that produces an unnamed
temporary result.
5. The name of the M-file being executed is available within a function in the variable
myfilename. For example, when the M-file myfunction.m is being executed, the
workspace of the function contains the variable myfilename, which contains the
character string ‘myfunction’. This variable also exists within script files, in which
case it contains the name of the script file being executed.
FUNCTION M-FILES AND THE MATLAB SEARCH PATH
Function M-files are one of the fundamental strengths of MATLAB. They allow one to
encapsulate sequences of useful commands and apply them over and over. Since M-files
exist as text files on disk, it is important that MATLAB maximize the speed at which the
files are found, opened, and executed. The techniques that MATLAB uses to maximize
speed are as follows:
1. The first time MATLAB executes a function M-file, it opens the corresponding text
file and compiles the commands into an internal pseudocode representation in
memory that speeds execution for all later calls to the function. If the function
contains references to other M-file functions and script M-files, they too are compiled
into memory.
2. The function inmem returns a cell array of strings containing a list of functions and
script files currently compiled into memory.
3. It is possible to store the compiled or P-Code version of a function M-file to disk
using the pcode command. When this is done, MATLAB loads the compiled function
into memory rather than the M-file. For most functions this step does not significantly
shorten the amount of time required to execute a function the first time. However, it
can speed up large M-files associated with complex graphical user interface functions.
P-Code files are created by issuing
>> pcode myfunction
where myfunction.m is the M-file name to be compiled. P-Code files are platform-
independent binary files that have the same name as the original M-file, but end in .p
rather than .m. P-Code files also provide a level of security, since they are visually
undecipherable and can be run without the corresponding M-file.
4. When MATLAB encounters a name that it does not recognize, it follows a set of rules
to determine what to do. Given the information presented here, the set of rules can
be updated as follows:
When you enter cow at the MATLAB prompt or if MATLAB encounters a reference
to cow in a script or function M-file,
1. it checks to see if cow is a variable in the current workspace; if not,
2. it checks to see if cow is a built-in function; if not,
APPLICATION ORIENTATION IN ENGINEERING MATHEMATICS
AND MATHEMATICAL MODELING , SV NIT, SURAT Dec 26-30,2006.- 54
3. it checks to see if cow is a subfunction in the M-file in which cow
appears; if not,
4. it checks to see if cow.p and then cow.m is a private function to the
M-file in which cow appears; if not,
5. it checks to see if cow.p and then cow.m exists in the current
directory; if not,
6. it checks to see cow.p and then cow.m exists in each directory
specified on the MATLAB search path, by searching in the order in
which the search path is specified.
MATLAB uses the first match it finds.
5. When MATLAB is started, it caches the name and location of all M-files stored
within the toolbox subdirectory and in all subdirectories of the toolbox directory.
This allows MATLAB to find and execute function M-files much faster. It also makes
the command lookfor work faster.
In the development of M-file functions, it is best to store them outside the toolbox
directory, perhaps in the MATLAB directory, until they are considered complete.
When they are complete, move them to a subdirectory inside the read only toolbox
directory. Finally, make sure the MATLAB search path is changed to recognize their
existence.
NOTE: M-file functions that are cached are considered read-only. If they are executed
and then later altered, MATLAB will simply execute the function that was previously
compiled into memory, ignoring the changed M-files. Moreover, if new M-files are added
within are added within the toolbox directory after MATLAB is running, their presence
will not be noted in the cache, and thus they will be unavailable for use.
6. When new M-files are added to a cached location, MATLAB will find them only if
the cache is refreshed by issuing the command path(path). On the other hand, when
cached M-files are modified, MATLAB will recognize the changes only if a
previously compiled version is dumped from memory by issuing the clear command.
7. MATLAB keeps track of the modification date of M-files outside the toolbox
directory. As a result, when an M-file function is encountered that was previously
compiled into memory, MATLAB compares the modification dates of the compiled
M-file with that of the M-file on disk. If the dates are the same, MATLAB executes
the compiled M-file. On the other hand, if the M-file and compiles the newer, revised
M-file for execution.
NOTE: You can also create your own toolboxes.
Solving ordinary differential equation:
We can solve a system of differential equations using MATLAB, the function names for
that are ode45, ode23, ode113 etc. Out of which we are going to concentrate on ode45 only,
and the syntax rule for that is:
>> [x , t]=ode45(‘filename’,tspan,x0)
Suppose we have to solve:
dx1/dt = -x1(t)-t2 x2(t) ;
dx2/dt = -t2x1(t)-x2(t)
x1(0)=1 x2(0)=1 on [0,1].
APPLICATION ORIENTATION IN ENGINEERING MATHEMATICS
AND MATHEMATICAL MODELING , SV NIT, SURAT Dec 26-30,2006.- 55
Here we have to create a new file suppose the file name is orddiff.m. In that file we have
to write the above system of differential equation, and for that we write a function:
function y = filename (t, x)
y = [system of differential equations]
i.e. we write :
function y = orddiff(t,x)
y = [-x(1)-t .^2*x(2); -t .^2*x(1)-x(2)]
After doing this go to command prompt. Here initial conditions are [1 1]’ so our x0=[1 1]’
and we have to solve this ode on [0 1] so our tspan=[0 1], then
>> [x t] = ode45(‘orddiff’,tspan,x0)
will solve this system of differential equations.
Finding minimum of a function:
We can find minimum of a function in an interval using MATLAB, the function names for
that are fmin, fmins. Here we give example of fmin only, the syntax rule for that is:
>> X= fmin(‘filename’,x1,x2)
Suppose we have to find minimum of :
f(x) = x.^2 over the interval [2, 4]
Here we have to create a new file suppose the file name is rkgmin.m. In that file we have
to write the above function, and for that we write a function:
function y = filename (x)
y = function
i.e. we write :
function y = rkgmin(x)
y = x .^2;
After doing this go to command prompt. Here the interval on which we have to find the
minimum is [2, 4] so our x1 = 2 and x2 = 4. On command prompt now you type:
>>X = fmin(‘rkgmin’,x1,x2)
will solve this system of differential equations.
We give below the major functions available in various tool boxes in MATLAB.
These functions are changing slightly with new updates of the software. Use helpwin to get
these changes.
Reference:
Rudra Pratap : Getting started with MATLAB 7, Oxford University Press, 2007.
APPLICATION ORIENTATION IN ENGINEERING MATHEMATICS
AND MATHEMATICAL MODELING , SV NIT, SURAT Dec 26-30,2006.- 56
Table of functions in soft computing components Tool boxes
Fuzzy logic tool box:
GUI editors Membership functions
Anfisedit - ANFIS training and testing GUI dsigmf - Difference of two sigmoid
tool. membership functions.
Findcluster - Clustering UI tool. gauss2mf - Two-sided Gaussian curve
fuzzy - Basic FIS editor. membership function.
mfedit - Membership function editor. gaussmf - Gaussian curve membership
ruleedit - Rule editor and parser. function.
ruleview - Rule viewer and fuzzy inference gbellmf - Generalized bell curve
diagram. membership function.
surfview - Output surface viewer. pimf - Pi-shaped curve membership
function.
psigmf - Product of two sigmoid
membership functions.
smf - S-shaped curve membership
function.
sigmf - Sigmoid curve membership
function.
trapmf - Trapezoidal membership function.
trimf - Triangular membership function.
zmf - Z-shaped curve membership
function.
Miscellaneous functions
convertfis - Convert v1.0 fuzzy matrix to v2.0 fuzzy structure.
discfis - Discretize a fuzzy inference system.
evalmmf - For multiple membership functions evaluation.
fstrvcat - Concatenate matrices of varying size.
fuzarith - Fuzzy arithmatic function.
findrow - Find the rows of a matrix that match the input string.
genparam - Generates initial premise parameters for ANFIS learning.
nextline - Return next line of a text files.
probor - Probabilistic OR.
sugmax - Maximum output range for a Sugeno system.
APPLICATION ORIENTATION IN ENGINEERING MATHEMATICS
AND MATHEMATICAL MODELING , SV NIT, SURAT Dec 26-30,2006.- 57
Command line FIS functions Advanced techniques
addmf - Add membership function to FIS anfis - Training routine for Sugeno-type
addrule - Add rule to FIS. FIS (MEX only).
addvar - Add variable to FIS. fcm - Find clusters with fuzzy c-means
defuzz - Defuzzify membership function. clustering.
evalfis - Perform fuzzy inference genfis1 - Generate FIS matrix using generic
calculation. method.
evalmf - Generic membership function genfis2 - Generate FIS matrix using
evaluation. subtractive clustering.
gensurf - Generate FIS output surface. subclust - Estimate cluster centers with
getfis - Get fuzzy system properties. subtractive clustering.
mf2mf - Translate parameters between GUI helper files
functions. cmfdlg - Add customized membership
newfis - Create new FIS. function dialog.
Parsrule - Parse fuzzy rules. cmthdlg - Add customized inference method
plotfis - Display FIS input-output diagram. dialog.
plotmf - Display all membership functions fisgui - Generic GUI handling for the
for one variable. Fuzzy Logic Toolbox
readfis - Load FIS from disk. gfmfdlg - Generate fis using grid partition
rmmf - Remove membership function method dialog.
from FIS. mfdlg - Add membership function dialog.
rmvar - Remove variable from FIS. mfdrag - Drag membership functions using
setfis - Set fuzzy system properties. mouse.
showfis - Display annotated FIS. popundo - Pull the last change off the undo
showrule - Display FIS rules. stack.
writefis - Save FIS to disk. pushundo - Push the current FIS data onto the
undo stack.
savedlg - Save before closing dialog.
statmsg - Display messages in a status field.
updtfis - Update Fuzzy Logic Toolbox
GUI tools.
wsdlg - Open from/save to workspace
dialog
Image processing Tool box:
Image display Image file I/O.
colorbar - Display colorbar (MATLAB imfinfo - Return information about image
Toolbox). file (MATLAB Toolbox).
getimage - Get image data from axes. imread - Read image file (MATLAB
image - Create and display image object Toolbox).
(MATLAB Toolbox). imwrite - Write image file (MATLAB
imagesc - Scale data and display as image Toolbox).
APPLICATION ORIENTATION IN ENGINEERING MATHEMATICS
AND MATHEMATICAL MODELING , SV NIT, SURAT Dec 26-30,2006.- 58
(MATLAB Toolbox). Geometric operations
immovie - Make movie from multiframe imcrop - Crop image.
indexed image. imresize - Resize image.
imshow - Display image. imrotate - Rotate image.
montage - Display multiple image frames as interp2 - 2-D data interpolation (MATLAB
rectangular montage. Toolbox).
subimage - Display multiple images in single Image analysis
figure. edge - Find edges in intensity image.
truesize - Adjust display size of image. qtdecomp - Perform quadtree decomposition.
warp - Display image as texture-mapped qtgetblk - Get block values in quadtree
surface. decomposition.
zoom - Zoom in and out of image or 2-D qtsetblk - Set block values in quadtree
plot (MATLAB Toolbox). decomposition.
Image enhancement Pixel values and statistics
histeq - Enhance contrast using histogram corr2 - Compute 2-D correlation
equalization. coefficient.
imadjust - Adjust image intensity values or imcontour - Create contour plot of image
colormap. data.
imnoise - Add noise to an image. imfeature - Compute feature measurements
medfilt2 - Perform 2-D median filtering. for image regions.
ordfilt2 - Perform 2-D order-statistic imhist - Display histogram of image data.
filtering. impixel - Determine pixel color values.
wiener2 - Perform 2-D adaptive noise- improfile - Compute pixel-value cross-
removal filtering. sections along line segments.
mean2 - Compute mean of matrix
Region-based processing elements.
roicolor - Select region of interest, based on pixval - Display information about image
color. pixels.
roifill - Smoothly interpolate within std2 - Compute standard deviation of
arbitrary region. matrix elements.
roifilt2 - Filter a region of interest.
roipoly - Select polygonal region of interest.
Linear filtering Linear 2-D filter design
conv2 - Perform 2-D convolution freqspace - Determine 2-D frequency
(MATLAB Toolbox). response spacing (MATLAB
convmtx2 - Compute 2-D convolution Toolbox).
matrix. freqz2 - Compute 2-D frequency response.
convn - Perform N-D convolution fsamp2 - Design 2-D FIR filter using
(MATLAB Toolbox). frequency sampling.
filter2 - Perform 2-D linear filtering ftrans2 - Design 2-D FIR filter using
(MATLAB Toolbox). frequency transformation.
fspecial - Create predefined filters. fwind1 - Design 2-D FIR filter using 1-D
window method.
fwind2 - Design 2-D FIR filter using 2-D
window method
Image transforms Neighborhood and block processing
dct2 - Compute 2-D discrete cosine bestblk - Choose block size for block
APPLICATION ORIENTATION IN ENGINEERING MATHEMATICS
AND MATHEMATICAL MODELING , SV NIT, SURAT Dec 26-30,2006.- 59
transform. processing.
dctmtx - Compute discrete cosine transform blkproc - Implement distinct block
matrix. processing for image.
fft2 - Compute 2-D fast Fourier transform col2im - Rearrange matrix columns into
(MATLAB Toolbox). blocks.
fftn - Compute N-D fast Fourier colfilt - Perform neighborhood operations
transform (MATLAB Toolbox). using columnwise functions.
fftshift - Reverse quadrants of output of im2col - Rearrange image blocks into
FFT (MATLAB Toolbox). columns.
idct2 - Compute 2-D inverse discrete nlfilter - Perform general sliding-
cosine transform. neighborhood operations.
ifft2 - Compute 2-D inverse fast Fourier Color space conversions
transform (MATLAB Toolbox). hsv2rgb - Convert HSV values to RGB
ifftn - Compute N-D inverse fast Fourier color space (MATLAB Toolbox).
transform (MATLAB Toolbox). ntsc2rgb - Convert NTSC values to RGB
iradon - Compute inverse Radon transform. color space.
phantom - Generate a head phantom image. rgb2hsv - Convert RGB values to HSV
radon - Compute Radon transform. color space (MATLAB Toolbox).
rgb2ntsc - Convert RGB values to NTSC
color space.
rgb2ycbcr - Convert RGB values to YCBCR
color space.
ycbcr2rgb - Convert YCBCR values to GB
color space.
Colormap manipulation Image types and type conversions
brighten - Brighten or darken colormap dither - Convert image using dithering.
(MATLAB Toolbox). gray2ind - Convert intensity image to
cmpermute - Rearrange colors in colormap. indexed image.
cmunique - Find unique colormap colors grayslice - Create indexed image from
and corresponding image. intensity image by thresholding.
colormap - Set or get color lookup table im2bw - Convert image to binary image
(MATLAB Toolbox). by thresholding.
imapprox - Approximate indexed image by im2double - Convert image array to double
one with fewer colors. precision.
rgbplot - Plot RGB colormap im2uint8 - Convert image array to 8-bit
components (MATLAB unsigned integers.
Toolbox).
Binary image operations Continue….. image types and type
applylut - Perform neighborhood operations conversions
using lookup tables. ind2gray - Convert indexed image to
bwarea - Compute area of objects in binary intensity image.
image. ind2rgb - Convert indexed image to RGB
bweuler - Compute Euler number of binary image.
image. isbw - Return true for binary image.
bwfill - Fill background regions in binary isgray - Return true for intensity image.
image. isind - Return true for indexed image.
APPLICATION ORIENTATION IN ENGINEERING MATHEMATICS
AND MATHEMATICAL MODELING , SV NIT, SURAT Dec 26-30,2006.- 60
bwlabel - Label connected components in isrgb - Return true for RGB image.
binary image. mat2gray - Convert matrix to intensity
bwmorph - Perform morphological image.
operations on binary image. rgb2gray - Convert RGB image or colormap
bwperim - Determine perimeter of objects in to grayscale.
binary image. rgb2ind - Convert RGB image to indexed
bwselect - Select objects in binary image. image.
dilate - Perform dilation on binary image.
erode - Perform erosion on binary image.
makelut - Construct lookup table for use
with applylut
Neural network tool box:
Adapt functions Layer initialization functions
adaptwb - By-weight-and-bias network initnw - Nguyen-Widrow layer initializion
adaption function. function.
initwb - By-weight-and-bias layer
initialization function.
Analysis functions Line search functions
errsurf - Error surface of single input srchbac - Backtracking search.
neuron. srchbre - Brent's combination golden
maxlinlr - Maximum learning rate for a linear section/quadratic interpolation.
layer. srchcha - Charalambous' cubic interpolation.
srchgol - Golden section search.
srchhyb - Hybrid bisection/cubic search.
Distance functions Net input functions
boxdist - Box distance function. netprod - Product net input function.
dist - Euclidiean distance weight netsum - Sum net input function.
function.
mandist - Manhattan distance weight
function.
linkdist - Link distance function.
Learning functions New networks
learncon - Conscience bias learning network - Create a custom neural network.
function. newc - Create a competitive layer.
learngd - Gradient descent weight/bias newcf - Create a cascade-forward
learning function. backpropagation network.
learngdm - Gradient descent w/momentum newelm - Create an Elman backpropagation
weight/bias learning function. network.
learnh - Hebb weight learning function. newff - Create a feed-forward
learnhd - Hebb with decay weight learning backpropagation network.
function. newfftd - Create a feed-forward input-delay
learnis - Instar weight learning function. backprop network.
learnk - Kohonen weight learning newgrnn - Design a generalized regression
function. neural network.
APPLICATION ORIENTATION IN ENGINEERING MATHEMATICS
AND MATHEMATICAL MODELING , SV NIT, SURAT Dec 26-30,2006.- 61
learnlv1 - LVQ1 weight learning function. newhop - Create a Hopfield recurrent
learnlv2 - LVQ2 weight learning function. network.
learnos - Outstar weight learning function. newlin - Create a linear layer.
learnp - Perceptron weight/bias learning newlind - Design a linear layer.
function. newlvq - Create a learning vector
learnpn - Normalized perceptron quantization network.
weight/bias learning function. newp - Create a perceptron.
learnsom - Self-organizing map weight newpnn - Design a probabilistic neural
learning function. network.
learnwh - Widrow-Hoff weight/bias learning newrb - Design a radial basis network.
rule. newrbe - Design an exact radial basis
network.
newsom - Create a self-organizing map.
Net input derivative functions Performance functions
dnetprod - Product net input derivative mae - Mean absolute error performance
function. function.
dnetsum - Sum net input derivative function. mse - Mean squared error performance
Network initialization functions function.
iitlay - Layer-by-layer network msereg - Mean squared error with
initialization function. regularization performance
function.
sse - Sum squared error performance
function.
Performance derivative functions Plotting functions
dmae - Mean absolute error performance hintonw - Hinton graph of weight matrix.
derivatives function. hintonwb - Hinton graph of weight matrix
dmse - Mean squared error performance and bias vector.
derivatives function. plotbr - Plot network performance for
dmsereg - Mean squared error w/reg Bayesian regularization training.
performance derivative function. plotes - Plot an error surface of a single
dsse - Sum squared error performance input neuron.
derivative function. plotpc - Plot classification line on
perceptron vector plot.
plotpv - Plot perceptron input/target
vectors.
Pre and Post Processing Plotep - Plot a weight-bias position on an
prestd - Normalize data for unity error surface.
standard deviation and zero plotperf - Plot network performance.
mean. plotsom - Plot self-organizing map.
poststd - Unnormalize data which has plotv - Plot vectors as lines from the
been normalized by PRESTD. origin.
trastd - Transform data with pre- plotvec - Plot vectors with different colors.
calculated mean and standard
deviation.
premnmx - Normalize data for maximum of
1 and minimum of -1.
APPLICATION ORIENTATION IN ENGINEERING MATHEMATICS
AND MATHEMATICAL MODELING , SV NIT, SURAT Dec 26-30,2006.- 62
Pre and Post Processing Simulink support
postmnmx - Unnormalize data which has gensim - Generate a SIMULINK block to
been normalized by simulate a neural network.
PREMNMX. Topology functions
tramnmx - Transform data with gridtop - Grid layer topology function.
precalculated minimum and hextop - Hexagonal layer topology function.
maximum. randtop - Random layer topology function.
prepca - Principal component analysis on Using networks
input data. sim - Simulate a neural network.
trapca - Transform data with PCA init - Initialize a neural network.
matrix computed by PREPCA. adapt - Allow a neural network to adapt.
postreg - Post-training regression train - Train a neural network.
analysis. disp - Display a neural network's
properties.
display - Display the name and properties of
a neural network variable.
Training functions Transfer functions
trainbfg - BFGS quasi-Newton compet - Competitive transfer function.
backpropagation. hardlim - Hard limit transfer function.
trainbr - Bayesian regularization. hardlims - Symmetric hard limit transfer
traincgb - Powell-Beale conjugate gradient function.
backpropagation. logsig - Log sigmoid transfer function.
traincgf - Fletcher-Powell conjugate poslin - Positive linear transfer function.
gradient backpropagation. purelin - Linear transfer function.
traincgp - Polak-Ribiere conjugate gradient radbas - Radial basis transfer function.
backpropagation. satlin - Saturating linear transfer
traingd - Gradient descent backpropagation. function.
traingdm - Gradient descent with momentum satlins - Symmetric saturating linear
backpropagation. transfer function.
traingda - Gradient descent with adaptive lr softmax - Soft max transfer function.
backpropagation. tansig - Hyperbolic tangent sigmoid
traingdx - Gradient descent w/momentum & transfer function.
adaptive lr backpropagation. tribas - Triangular basis transfer
trainlm - Levenberg-Marquardt function.
backpropagation.
trainoss - One step secant backpropagation.
trainrp - Resilient backpropagation (Rprop).
trainscg - Scaled conjugate gradient
backpropagation.
trainwb - By-weight-and-bias network
training function.
trainwb1 - By-weight-&-bias 1-vector-at-a-
time training function.
APPLICATION ORIENTATION IN ENGINEERING MATHEMATICS
AND MATHEMATICAL MODELING , SV NIT, SURAT Dec 26-30,2006.- 63
For functions listed by network type Transfer derivative functions
dhardlim - Hard limit transfer derivative
assoclr - Associative learning rules. function.
backprop - Backpropagation networks. dhardlms - Symmetric hard limit transfer
elman - Elman recurrent networks. derivative function.
hopfield - Hopfield recurrent networks. dlogsig - Log sigmoid transfer derivative
linnet - Linear networks. function.
lvq - Learning vector quantization. dposlin - Positive linear transfer derivative
percept - Perceptrons. function.
radbasis - Radial basis networks. dpurelin - Hard limit transfer derivative
selforg - Self-organizing networks. function.
dradbas - Radial basis transfer derivative
function.
dsatlin - Saturating linear transfer derivative
function.
dsatlins - Symmetric saturating linear transfer
derivative function.
dtansig - Hyperbolic tangent sigmoid
transfer derivative function.
dtribas - Triangular basis transfer derivative
function.
Update networks from previous versions Vectors
nnt2c - Update NNT 2.0 competitive layer cell2mat - Combine cell array of matrices
to NNT 3.0. into one matrix.
nnt2elm - Update NNT 2.0 Elman concur - Create concurrent bias vectors.
backpropagation network to NNT con2seq - Convert concurrent vectors to
3.0. sequential vectors.
nnt2ff - Update NNT 2.0 feed-forward combvec - Create all combinations of
network to NNT 3.0. vectors.
nnt2hop - Update NNT 2.0 Hopfield ind2vec - Convert indices to vectors.
recurrent network to NNT 3.0. mat2cell - Break matrix up into cell array of
nnt2lin - Update NNT 2.0 linear layer to matrices.
NNT 3.0. minmax - Ranges of matrix rows.
nnt2lvq - Update NNT 2.0 learning vector nncopy - Copy matrix or cell array.
quantization network to NNT 3.0. normc - Normalize columns of a matrix.
nnt2p - Update NNT 2.0 perceptron to normr - Normalize rows of a matrix.
NNT 3.0. pnormc - Pseudo-normalize columns of a
nnt2rb - Update NNT 2.0 radial basis matrix.
network to NNT 3.0. quant - Discretize values as multiples of
nnt2som - Update NNT 2.0 self-organizing a quantity.
map to NNT 3.0. seq2con - Convert sequential vectors to
concurrent vectors.
sumsqr - Sum squared elements of matrix.
vec2ind - Convert vectors to indices.
APPLICATION ORIENTATION IN ENGINEERING MATHEMATICS
AND MATHEMATICAL MODELING , SV NIT, SURAT Dec 26-30,2006.- 64
Weight functions Weight and bias initialization functions
dist - Euclidean distance weight initcon - Conscience bias initialization
function. function.
dotprod - Dot product weight function. initzero - Zero weight/bias initialization
mandist - Manhattan distance weight function.
function. midpoint - Midpoint weight initialization
negdist - Dot product weight function. function.
normprod - Normalized dot product weightrandnc - Normalized column weight
function. initialization function.
randnr - Normalized row weight
initialization function.
Weight derivative functions rands - Symmetric random weight/bias
ddotprod - Dot product weight derivative initialization function
function.
Wavelet toolbox:
Wavelets: General Wavelet Families
biorfilt - Biorthogonal wavelet filter set. biorwavf - Biorthogonal spline wavelet
dyaddown - Dyadic downsampling. filters.
dyadup - Dyadic upsampling. coifwavf - Coiflets wavelet filters.
intwave - Integrate wavelet function psi. dbaux - Daubechies wavelet filters
orthfilt - Orthogonal wavelet filter set. computation.
qmf - Quadrature mirror filter. dbwavf - Daubechies wavelet filters.
wavefun - Wavelet and scaling functions. mexihat - Mexican hat wavelet.
wavemngr - Wavelet manager. meyer - Meyer wavelet.
wfilters - Wavelet filters. meyeraux - Meyer wavelet auxiliary
wmaxlev - Maximum wavelet function.
decomposition level. morlet - Morlet wavelet.
symwavf - Symlets wavelet filters.
Continuous Wavelet: 1-D
cwt - Continuous wavelet coefficients 1-D.
Discrete Wavelets: 1-D Discrete Wavelets: 2-D
appcoef - Extract 1-D approximation appcoef2 - Extract 2-D approximation
coefficients. coefficients.
detcoef - Extract 1-D detail coefficients. detcoef2 - Extract 2-D detail coefficients.
dwt - Single-level discrete 1-D wavelet dwt2 - Single-level discrete 2-D wavelet
transform. transform.
dwtper - Single-level discrete 1-D wavelet dwtper2 - Single-level discrete 2-D wavelet
transform (periodized). transform (periodized).
dwtmode - Discrete wavelet transform dwtmode - Discrete wavelet transform
extension mode. extension mode.
idwt - Single-level inverse discrete 1-D idwt2 - Single-level inverse discrete 2-D
wavelet transform. wavelet transform.
APPLICATION ORIENTATION IN ENGINEERING MATHEMATICS
AND MATHEMATICAL MODELING , SV NIT, SURAT Dec 26-30,2006.- 65
idwtper - Single-level inv. discrete 1-D idwtper2 - Single-level inv. discrete 2-D
wavelet transform (periodized). wavelet transform (periodized).
upcoef - Direct reconstruction from 1-D upcoef2 - Direct reconstruction from 2-D
wavelet coefficients. wavelet coefficients.
upwlev - Single-level reconstruction of 1-D upwlev2 - Single-level reconstruction of 2-D
wavelet decomposition. wavelet decomposition.
wavedec - Multi-level 1-D wavelet wavedec2 - Multi-level 2-D wavelet
decomposition. decomposition.
waverec - Multi-level 1-D wavelet waverec2 - Multi-level 2-D wavelet
reconstruction. reconstruction.
wrcoef - Reconstruct single branch from 1- wrcoef2 - Reconstruct single branch from 2-
D wavelet coefficients D wavelet coefficients.
Wavelets Packets Algorithms De-noising and Compression for Signals
besttree - Best tree (wavelet packet). and Images
bestlevt - Best level tree (wavelet packet). ddencmp - Default values for de-noising or
entrupd - Entropy update (wavelet packet). compression.
wentropy - Entropy(wavelet packet). thselect - Threshold selection for de-
wp2wtree - Extract wavelet tree from wavelet noising.
packet tree. wden - Automatic 1-D de-noising
wpcoef - Wavelet packet coefficients. using wavelets.
wpcutree - Cut wavelet packet tree. wdencmp - De-noising or compression
wpdec - Wavelet packet decomposition 1-D. using wavelets.
wpdec2 - Wavelet packet decomposition 2-D. wnoise - Generate noisy wavelet test
wpfun - Wavelet packet functions. data.
wpjoin - Recompose wavelet packet. wnoisest - Estimate noise of 1-D wavelet
wprcoef - Reconstruct wavelet packet coefficients.
coefficients. wpdencmp - De-noising or compression
wprec - Wavelet packet reconstruction 1-D. using wavelet packet.
wprec2 - Wavelet packet reconstruction 2-D. wpthcoef - Wavelet packet coefficients
wpsplt - Split (decompose) wavelet packet. thresholding.
wthcoef - Wavelet coefficients
thresholding 1-D.
wthcoef2 - Wavelet coefficients
thresholding 2-D.
wthresh - Perform soft or hard
thresholding.
APPLICATION ORIENTATION IN ENGINEERING MATHEMATICS
AND MATHEMATICAL MODELING , SV NIT, SURAT Dec 26-30,2006.- 66
Tree Management Utilities General Utilities
allnodes - Tree nodes. deblankl - Convert string to lowercase
depo2ind - Node depth-position to node without blanks.
index. errargn - Check function arguments
ind2depo - Node index to node depth- number.
position. errargt - Check function arguments type.
isnode - True for existing node. num2mstr - Convert number to string in
istnode - True for terminal nodes. maximum precision.
maketree - Make tree. wcodemat - Extended pseudocolor matrix
nodeasc - Node ascendants. scaling.
nodedesc - Node descendants. wcommon - Find common elements.
nodejoin - Recompose node. wkeep - Keep part of a vector or a matrix.
nodepar - Node parent. wrev - Flip vector.
nodesplt - Split (decompose) node.
ntnode - Number of terminal nodes.
plottree - Plot tree.
tnodes - Terminal nodes.
treedpth - Tree depth.
treeord - Tree order.
wdatamgr - Manager for data structure.
wtreemgr - Manager for tree structure.
APPLICATION ORIENTATION IN ENGINEERING MATHEMATICS
AND MATHEMATICAL MODELING , SV NIT, SURAT Dec 26-30,2006.- 67