You are on page 1of 16

ARTICLE IN PRESS

Nonlinear Analysis ( )
Contents lists available at ScienceDirect
Nonlinear Analysis
journal homepage: www.elsevier.com/locate/na
MatLab tutorial for scientific and engineering computations
International Federation of Nonlinear Analysts (IFNA);
2008 World Congress of Nonlinear Analysts (WCNA)
S.K. Sen
a
, Gholam Ali Shaykhian
b,
a
Department of Mathematical Sciences, Florida Institute of Technology, 150 West University Boulevard, Melbourne, FL 32901-6975, United States
b
National Aeronautics and Space Administration (NASA), Kennedy Space Center, FL 32899, United States
a r t i c l e i n f o
Keywords:
MatLab
Symbolic calculations
Matrix manipulations
Graphical functions
a b s t r a c t
The computing scenario over centuries/millenniums has been changing based on the
tools/power of tools often innovative available to mankind. We discuss here in tutorial
form various features of MatLab and their usage to solve problems. MatLab is one of the
most widely used, very high level programming languages for scientific and engineering
computations. It is very user-friendly and needs practically no formal programming
knowledge. Presented here are MatLab programming aspects and not just the MatLab
commands for scientists and engineers who do not have formal programming training and
also have no significant time to spare for learning programming to solve their real world
problems. Specifically provided are programs for visualization. Also, stated are the current
limitations of the MatLab, which possibly can be taken care of by Mathworks Inc. in a future
version to make MatLab more versatile.
Published by Elsevier Ltd
1. Introduction
The following topics are presented in this tutorial; brief explanations and examples are given for each topic to expose
the MatLab features to aid learning.
Introducing MatLab
MatLab operators and notations
MatLab keywords
Scalar, vector and matrix in MatLab
Getting started
Array editor
Work with matrix
Elementary matrix manipulations
Matrix arithmetic operations
MatLab mathematical functions
MatLab graphical functions
Symbolic calculations
MatLab symbolic functions

Corresponding author. Tel.: +1 321 861 2336; fax: +1 321 861 0104.
E-mail addresses: sksen@fit.edu (S.K. Sen), ali.shaykhian@nasa.gov (G.A. Shaykhian).
0362-546X/$ see front matter. Published by Elsevier Ltd
doi:10.1016/j.na.2009.01.069
Please cite this article in press as: S.K. Sen, G.A. Shaykhian, MatLab tutorial for scientific and engineering computations, Nonlinear Analysis (2009),
doi:10.1016/j.na.2009.01.069
ARTICLE IN PRESS
2 S.K. Sen, G.A. Shaykhian / Nonlinear Analysis ( )
2. Introducing MatLab
MatLab is a mathematical computation tool which is available commercially. Other mathematical computation tools
include Maple, Mathematica and MathCad. MatLab is an abbreviation for MATrix LABoratory. MatLab is a numerical
computation and simulation tool. MatLab can be used as a glorified calculator; its real strength is in matrix manipulations.
MatLab does purely numerical calculations. Computer algebra functionalities are achieved within the MatLab environment
using symbolic toolbox. Note: Computer algebra programs, such as MAPLE or MATHEMATICA provide support for
calculating with mathematical equations using symbolic operations (as a person would normally do with paper and pencil).
MatLab is a programming language which supports data structure Structure, which is similar to the data structure Struct of
the C++ programming language, or fromthe so-called cell arrays to the definition of classes in object oriented programming.
MatLab is equipped with all the essential constructs of a higher programming language. MatLab is an interpreter
programming language (command interface). MatLab is packaged with an editor and debugging functionality. Debugging is
useful to analysis large MatLab programs and find errors. MatLab can be used interactively or by writing programs.
MatLab Variables are declared by assigning a value or an expression to the variable, for example:
A = 3; value 3 is assigned to the variable A and A = A + 25; 25 is added to variable A and is assigned to A. MatLab
requires all variable names to start with letters aZ or underscore. Once a variable is defined, it can be used in subsequent
calculations. Variable names are case sensitive and keywords cannot be used as variable names (use command iskeyword
to list MatLab keywords; iskeyword returns a cell array containing the MatLab keywords). The MatLab command who
and whos provide useful informationregarding variables. The command who lists the variables inthe current workspace
and the command whos lists more information about each variable.
To reclaim memory occupied by a variable, use command clear; clear command clears a variable from memory.
Examples:
A =3;
who
Your variables are:
A
whos
Name Size Byte class
A 1x1 8 Double array
Grand total is 1 elements using 8 bytes.
MatLab will let you use built-in function names as variables (it is a really bad idea).
sin = 3 changes sin from a function to a variable name.
3. MatLab operators and notations
MatLab operators are listed below with brief descriptions.
+ for matrix or element addition
- for matrix or element subtraction
.* for element multiplication
* for matrix multiplication
./ for element division
/ for right matrix division (right multiplication by an inverse)
\ for left matrix division (left multiplication by an inverse)
. for raising an element to a power
for raising a matrix to a power
for converting to complex conjugate transpose
[] for vector and matrix delimiter
() for grouping, vector and matrix element indices, function argument delimiter
: for index range separator
; for matrix row separator
blank space for matrix column element separator
, comma for matrix index separator, function argument separator
. period for radix expansion separator (American convention)
single forward quotes for demarcation of character strings
== for equality
& for AND
| for inclusive OR,
for NOT
<= for less than or equal,
Please cite this article in press as: S.K. Sen, G.A. Shaykhian, MatLab tutorial for scientific and engineering computations, Nonlinear Analysis (2009),
doi:10.1016/j.na.2009.01.069
ARTICLE IN PRESS
S.K. Sen, G.A. Shaykhian / Nonlinear Analysis ( ) 3
>= for greater than or equal
= for not equal,
1 for true,
0 for false.
% Ignore Further Text comment for rest of the line
: end of the line
. . . Continue on next line
MatLab prompt
c control-c to stop execution and return to prompt
q control-q to stop execution and exit MatLab
Order of Operations
Parentheses ()
Exponentiation
Multiplication *, division /
Addition +, subtraction -
4. MatLab keywords
MatLab key words should not be used for variable names; the command iskeyword returns a list of MatLab keywords
as shown below:
iskeyword
ans =
break
case
catch
continue
else
elseif
end
for
function
global
if
otherwise
persistent
return
switch
try
while
5. Scalar, vector and matrix in MatLab
In MatLab, a matrix with one row and one column is known as a scalar; vector is a one-dimensional matrix (row or
column) and matrix is considered as two-dimensional. Examples:
Scalar
17+6
ans = 23
A= 23+2
ans = 25
Row Vector There are different ways to declare a row vector; A row vector with 5 different elements is declared and
initialized below:
a = [1, 2, 3, 4, 5]
a = [1 2 3 4 5]
a = 1:5
a = [1:5]
Column vector Column vector is defined by using a ; between each element of the vector; Column vector can also be
created by transposing a row vector; Single quote () is used to transpose a matrix.
b = [1; 2; 3; 4; 5]
b = a
Please cite this article in press as: S.K. Sen, G.A. Shaykhian, MatLab tutorial for scientific and engineering computations, Nonlinear Analysis (2009),
doi:10.1016/j.na.2009.01.069
ARTICLE IN PRESS
4 S.K. Sen, G.A. Shaykhian / Nonlinear Analysis ( )
Fig. 1. Numeric format.
Matrix (two-dimensional)
m = [1.2, 3, 4; -3.7, -2, 5; 1, 2, 3]
m =
1.2000 3.0000 4.0000
3.7000 2.0000 5.0000
1.0000 2.0000 3.0000
Note: The default representation of numeric values can be changed through the File>Preferences>Numeric Format (Fig. 1).
6. Getting started
MatLab program can be started from the user desktop through the graphic icon; this icon created during installations.
Once the MatLab is loaded, the command interface (Fig. 1) is displayed.
is the command prompt for MatLab Professional version.
EDU is the command prompt for the Education version.
The main elements of this command interface are:
1. Command Window In Command window area, enter variables, run functions and m-files
2. Workspace In Workspace browser, variables may be viewed, manipulated, saved, and cleared
3. Launch Pad Easy access to tools, demos and documentations
4. Command History Keeps lines entered in Command Window, previously used variables or functions can be copies and
executed in Command Window
5. Current Directory Shows the current directory, the directory can be changed by right clicking the MatLab shortcut,
then select properties option, specify the directory in the start in field (Fig. 2)
6. Menu choice for the current directory,
7. Shortcut toolbar
Note Use the arrow in any of the Windows to undock it from desktop (to move a window outside of the desktop).
7. Array editor
Array Editor can be used to conveniently initialize a large array, in workspace, double click on a variable (or a group of
variables hold Ctrl key, click on variables) to open the MatLab Array Editor. In Array Editor (variables are used similar to
Microsoft Excel) changes to dimension of the matrix or individual entries can be made. In Array Editor Exchange data
between Microsoft Excel and MatLab is done through copy/paste (Fig. 3).
8. Work with matrix
One of the main capabilities of MatLab is its matrix processing. In the following few examples, we exploit the MatLab
matrix capabilities.
Please cite this article in press as: S.K. Sen, G.A. Shaykhian, MatLab tutorial for scientific and engineering computations, Nonlinear Analysis (2009),
doi:10.1016/j.na.2009.01.069
ARTICLE IN PRESS
S.K. Sen, G.A. Shaykhian / Nonlinear Analysis ( ) 5
Fig. 2. The MatLab command interface.
Fig. 3. Array editor.
Add extra row to a Matrix Add extra column to a Matrix
a = [1 2 4;2 4 6] a = [1 2 4; 2 4 6];
a = a = [a, [9; 9] ]
1 2 4 a =
2 4 6 1 2 4 9
a = [a; 7 7 7] 2 4 6 9
a = a = [1 2 4; 2 4 6];
1 2 4 v = [9; 9];
2 4 6 a = [a, v]
7 7 7 a =
1 2 4 9
2 4 6 9
Delete a row/ column from a Matrix % delete second column
a = [2 4 6; 3 5 7;1 8 9] a(:,2) = [ ]
a = a =
2 4 6 2 6
3 5 7 3 7
1 8 9 1 9
Please cite this article in press as: S.K. Sen, G.A. Shaykhian, MatLab tutorial for scientific and engineering computations, Nonlinear Analysis (2009),
doi:10.1016/j.na.2009.01.069
ARTICLE IN PRESS
6 S.K. Sen, G.A. Shaykhian / Nonlinear Analysis ( )
% delete third row a = [2 4 6; 3 5 7;1 8 9]
a(3,:) = [ ] a =
a = 2 4 6
2 4 6 3 5 7
3 5 7 1 8 9
% select the first row of Matrix a and assign it to vector
b
Select a row/ column from a Matrix and assign it to a vector
b = a(1,:) a = [2 4 6; 3 5 7; 1 8 9]
b = a =
2 4 6 2 4 6
a = [2 4 6; 3 5 7; 1 8 9] 3 5 7
a = 1 8 9
2 4 6
3 5 7
1 8 9
Colon Operator:
Used to define new matrices % select the second column of Matrix a and assign it to vector b
Modify existing matrices
Extract data from existing matrices
M(:) Converts a two-dimensional matrix to a
single column
b = a(:,2)
b =
4
5
8
To suppress the output of a MATLAB % Use... to continue definition of a matrix
calculation, the command must be ended in multiple lines
with a semicolon; the output of Matrix a is
suppressed in statement a =[2 4 6; 3 5 7;1 8 9]; a = [ 2 4 6;...
0 j 1;...
j j+1 -3]
a = [2 4 6; 3 5 7;1 8 9];
b = a(:,2)
b =
Use three periods (...) to break up
4 MATLAB command, when a command is too long.
5
8
Convert a matrix to a column vector use the MatLab colon
operator (:)
>b =[2 3;1 6;7 8];
9. Elementary matrix manipulations
MatLab help elmat command provides a complete list of elementary matrices and matrix manipulation commands;
partial listing is shown below:
help elmat
Elementary matrices
zeros Zeros array, Creates a matrix of all zeros.
ones Ones array, Creates a matrix of all ones.
eye Identity matrix.
repmat Replicate and tile array.
rand Uniformly distributed random numbers.
randn Normally distributed random numbers.
linspace Linearly spaced vector.
logspace Logarithmically spaced vector.
freqspace Frequency spacing for frequency response.
meshgrid X and Y arrays for 3-D plots.
: Regularly spaced vector and index into matrix.
Please cite this article in press as: S.K. Sen, G.A. Shaykhian, MatLab tutorial for scientific and engineering computations, Nonlinear Analysis (2009),
doi:10.1016/j.na.2009.01.069
ARTICLE IN PRESS
S.K. Sen, G.A. Shaykhian / Nonlinear Analysis ( ) 7
Basic array information
size Size of matrix, number of rows and columns.
length Length of vector.
ndims Number of dimensions.
numel Number of elements.
disp Display matrix or text.
isempty True for empty matrix.
isequal True if arrays are identical.
isnumeric True for numeric arrays.
islogical True for logical array.
logical Convert numeric values to logical.
MatLab zeros() function MatLab ones() function
zeros(N) function returns an N-by-N matrix of zeros ones(N) function returns an N-by-N matrix of ones
zeros(M,N) returns an M-by-N matrix of zeros ones(M,N) returns an M-by-N matrix of ones
Initialize a 3 3 matrix with zeros Initialize 2 3 matrix with ones
a = zeros(3,3) % initializes a 3 3 matrix to zeros b = ones(2,3)
b =
1 1 1
a = zeros(3); % initializes a 3 3 matrix to zeros 1 1 1
MatLab size() function MatLab length() function
size(X) returns the size of a matrix for M-by-N matrix X,
returns the two-element row vector D = [M, N] containing
the number of rows and columns in the matrix. For N-D
arrays, SIZE(X) returns a 1-by-N vector of dimension
lengths.
LENGTH(X) returns the length of (row or column) vector X
length(b)
size(b) ans =
ans =
2 3 3
Example: Initialize a vector to x
1
zeros, the number of elements of vector x
1
is equal to the number of columns in matrix b.
b x1 = zeros(length(b),1)
b = x1 =
1 1 1 0
1 1 1 0
0
Transpose of vector and matrix The operator is used to evaluate transpose of a matrix of a vector. A vector or a matrix is
transposed by placing the symbol after the matrix or vector to be transposed. Transpose the column vector x
1
, assign result
to vector x
2
.
x1=[3;5;7;9] x2=x1
x1 = x2 =
3 3 5 7 9
5
7
9
MatLab repmat() function the repmat() function
returns a replicate and tiles an array. In B = repmat(a,
M, N) creates a large matrix B consisting of an M-by-N,
tiling of copies of a.
MatLab end operator The end serves as the last index in an
indexing expression.
M = [1 2; 3 4; 5 6];
a = [1 2;3 4;5 6] M(:, end)=[ ] % delete the column of matrix M
a = M =
1 2 1
3 4 3
5 6 5
Please cite this article in press as: S.K. Sen, G.A. Shaykhian, MatLab tutorial for scientific and engineering computations, Nonlinear Analysis (2009),
doi:10.1016/j.na.2009.01.069
ARTICLE IN PRESS
8 S.K. Sen, G.A. Shaykhian / Nonlinear Analysis ( )
B = repmat(a,2,2) M = [1 2;3 4;5 6]
B = M =
1 2 1 2 1 2
3 4 3 4 3 4
5 6 5 6 5 6
1 2 1 2 M(end, :) = [ ] % delete the last row of matrix M
3 4 3 4 M =
5 6 5 6 1 2
3 4
10. Matrix arithmetic operations
MatLab matrix arithmetic operations are:
A+B
A-B
A*B A.*B
A\B A.\B
A/B A./B
A B A. B
A A.
Note: MatLab checks for the computational rules of matrix algebra, an error message is displayed when a rule is violated.
+ matrix addition is the operation of adding two matrices by
adding the corresponding entries together. A + B adds A and
B. A and B must have the same dimensions, unless one is
scalar.
- matrix subtraction is the operation of subtracting two
matrices by subtracting the corresponding entries
together. A - B subtracts B from A. A and B must have the
same dimensions, unless one is scalar.
A= [1 2; 3 4]; B=[3 5; 6 7]; A+B A= [1 2; 3 4]; B=[3 5; 6 7]; A-B
ans = ans =
4 7 -2 -3
9 11 -3 -3
* matrix multiplicationis the operation of multiplying two
matrices; an M L matrix A can be multiplied on the right
by an L N matrix B; the number of columns in the matrix
on the left A must equal the number of rows in the matrix on
the right B, unless one is a scalar. A*B is the linear algebraic
product of A and B.
.* term-by-term multiplication (array multiplication)
A.*B is the entry-by-entry product of A and B. A and B
must have the same dimensions, unless one is scalar.
M= [1 2; 3 4]
Note: A B = BA N=[3 5; 6 7]; K=M.*N
M= [1 2 3; 4 5 6 ]; K =
N = [2 3; 5 6; 2 7]; K = M*N 3 10
K = 18 28
18 36
45 84
Matrix division
MatLab supports two division operators, namely right division / and left division \.
\ Matrix left division. X = A\B solves the symbolic linear equations A*X=B. Note that A\B is roughly equivalent to inv(A)*B.
Warning messages are produced if X does not exist or is not unique. Rectangular matrices A are allowed, but the equations
must be consistent; a least squares solution is not computed.
.\ Array left division. A.\B is the matrix with entries B(i,j)/A(i,j). A and B must have the same dimensions, unless one is scalar.
/ Matrix right division. X=B/A solves the symbolic linear equation X*A=B. Note that B/A is the same as (A.\B.). Warning
messages are produced if X does not exist or is not unique. Rectangular matrices A are allowed, but the equations must be
consistent; a least squares solution is not computed.
./ Array right division. A./B is the matrix with entries A(i,j)/B(i,j). Aand B must have the same dimensions, unless one is scalar.
Matrix power. X P raises the square matrix X to the integer power P. If X is a scalar and P is a square matrix, X P raises X
to the matrix power P, using eigenvalues and eigenvectors. X P, where X and P are both matrices, is an error.
. Array power. A. B is the matrix with entries A(i,j) B(i,j). A and B must have the same dimensions, unless one is scalar.
Example: In X = A/B (right division), division is defined if B is invertible. In which case, X=A.B
1
(B
1
exists)
In X = A\B (left division), division is defined if A is invertible. In which case, X = A
1
.B (A
1
exists)
Please cite this article in press as: S.K. Sen, G.A. Shaykhian, MatLab tutorial for scientific and engineering computations, Nonlinear Analysis (2009),
doi:10.1016/j.na.2009.01.069
ARTICLE IN PRESS
S.K. Sen, G.A. Shaykhian / Nonlinear Analysis ( ) 9
Given linear systems of equations
Ax =

b
Solution (if exists) is defined by left division x = A/

b
X2 + X3 = 5
3X1 + X3 = 6
-X1 + X2 = 1
A= 0 1 1
3 0 1
-1 1 0
b = [5 ; 6; 1]
A = [0 1 1; 3 0 1; -1 1 0]; b = [5; 6; 1];
x = A\b % left division
x=
1.0000
2.0000
3.0000
Matrix Hermitian transpose. If A is complex, A is the complex conjugate transpose.
. Array transpose. A. is the real transpose of A. A. does not conjugate complex entries.
11. MatLab mathematical functions
There are over a hundred mathematical functions that come with the MatLab program; these are known as standard
(preprogrammed) mathematical functions. MatLab allows the standard functions to be redefined (one should avoid doing
so), however, in which case they lose their initial intended meanings. The MatLab standard functions are grouped by
their functions; for example, Trigonometric Functions, Exponential Functions, Complex Functions, Rounding and remainder
functions. Partial listing of selected preprogrammed mathematical functions is also shown below:
Trigonometric functions (partial list) Exponential functions (partial list)
acos Inverse cosine exp Exponential (e x)
cos Cosine log Natural logarithm
cosh Hyperbolic cosine log10 Common (base 10) logarithm
cot Cotangent sqrt Square root
Complex Functions (partial list) Rounding and remainder functions (partial list)
angle Phase angle ceil Round toward plus infinity
conj Complex conjugate fix Round toward zero
imag Complex imaginary part floor Round toward minus infinity
isreal True for noncomplex arrays
Statistical Functions (partial list) Discrete Mathematics (partial list)
mean arithmetic mean or average value of elements factor(x) returns a vector containing the prime factors of
x
min smallest component factorial(x) returns factorial of x
max largest component primes(x) generates a list of prime numbers less than or
equal to x
var variance of the elements in a vector isprime(x) returns 1 if the elements of x which are prime, 0
otherwise
cov variance of a vector or covariance of a matrix
12. MatLab graphical functions
Use MatLab help graph2d to list all MatLab two-dimensional graphical functions. The help graph3d lists the three-
dimensional graphical functions.
Two-dimensional graphical functions (partial list) Three-dimensional graphical
functions (partial list)
plot Linear plot (2D) plot3 Plot lines and points in 3-D
space
loglog Loglog scale plot mesh 3-D mesh surface
semilogx Semi-log scale plot surf 3-D colored surface
semilogy Semi-log scale plot fill3 Filled 3-D polygons
Please cite this article in press as: S.K. Sen, G.A. Shaykhian, MatLab tutorial for scientific and engineering computations, Nonlinear Analysis (2009),
doi:10.1016/j.na.2009.01.069
ARTICLE IN PRESS
10 S.K. Sen, G.A. Shaykhian / Nonlinear Analysis ( )
polar Polar coordinate plot. axis Control axis scaling and
appearance
plotyy Graphs with y tick labels on the left
and right
zoom Zoom in and out on a 2-D plot
bar for a vertical bar graph grid Grid lines
barh for a horizontal bar graph
stem for a stem plot
box Axis box
hold Hold current graph
axes Create axes in arbitrary position
Examples plot() function is used to plot a two-dimensional plot Color types Symbols Line
b blue solid . point -
g green dotted o circle :
r red dashdot x x-mark -.
c cyan dashed + plus - -
m magenta * star
y yellow s square
k black d diamond
v triangle (down)
triangle (up)
< triangle (left)
> triangle (right)
p pentagram
h hexagram
plot3() function is used to plot a three-dimensional plot
A plot can be made using various symbols, colors and line types
Line types, plot symbols and colors for plot() or plot3() functions are
represented through a character string
For example, a character string go: means a green dotted line with a
circle at each data point
plot(X,Y,go:) plots a green dotted line with a circle at each data point
plot3(X,Y,Z,ks-.) plots a black dashdot line with square at each point
Examples
angle = 0:pi/30:2*pi; Y = sin(angle); plot(angle, Y)
plot(angle, Y, r.: ) plots a red dotted line with a circle at
each data point
angle = 0:pi/30:2*pi; Y = sin(angle); plot(angle, Y, ro:)
Please cite this article in press as: S.K. Sen, G.A. Shaykhian, MatLab tutorial for scientific and engineering computations, Nonlinear Analysis (2009),
doi:10.1016/j.na.2009.01.069
ARTICLE IN PRESS
S.K. Sen, G.A. Shaykhian / Nonlinear Analysis ( ) 11
angle =0:0.1:1; plot(cos(2*pi*angle),
sin(2*pi*angle),ro-); axis square
angle =0:0.05:1;
plot(cos(2*pi*angle),
sin(2*pi*angle),ro-); axis square
Multiple function plots
angle = 0:pi/30:2*pi
f1 = exp(-2*angle); f2 = sin(angle*3); f3 = cos(angle*4)
plot(angle,[f1; f2; f3]) % or plot(angle, f1, angle, f2,
angle,f3)

Multiple Graphs with styles


angle = 0:pi/30:2*pi; f1 = exp(-2*angle); f2 =
sin(angle*3); f3 = cos(angle*4)
plot(angle,f1,ro:, angle, f2, g*-,angle, f3, bh)
angle = linspace(0,10*pi,100) % generates 100 points
between 0 and 10* pi
y = cos(angle); z = sin(angle)
plot3(angle, y, z); grid...
xlabel(Angle); ylabel(cos(x)); zlabel(sin(x))

angle = -5:0.01:5; plot3(cos(2*pi*angle),


sin(2*pi*angle),angle)
Please cite this article in press as: S.K. Sen, G.A. Shaykhian, MatLab tutorial for scientific and engineering computations, Nonlinear Analysis (2009),
doi:10.1016/j.na.2009.01.069
ARTICLE IN PRESS
12 S.K. Sen, G.A. Shaykhian / Nonlinear Analysis ( )
% A three-dimensional plot using the mesh command
x = (-3:0.1:3); % grid frame in x direction
y = (-3:0.1:3); % grid frame in y direction
v = ones(length(x),1); % auxiliary vector
X = v*x; % grid matrix of the x values
Y = y*v; % grid matrix of the y values
f = sin(X. 2+Y. 2).*exp(-0.2*(X. 2+Y. 2)); % function
value
mesh(X, Y, f) % mesh plot with mesh
zlabel(f = sin(X. 2+Y. 2).*exp(-0.2*(X. 2+Y. 2)))
xlabel(X)
ylabel(Y)
% A three-dimensional plot using the mesh command
x = [-2:0.2:2]; y = [-2:0.2:2];
[X,Y] = meshgrid(x,y);
Z=X.*exp(-X. 2-Y. 2);
mesh(X,Y,Z);
xlabel(X)
ylabel(Y)
zlabel(Z = X.*exp(-X. 2-Y. 2))
% A three-dimensional plot using the surf command
x = [-2:0.2:2]; y = [-2:0.2:2];
[X,Y] = meshgrid(x,y);
Z=X.*exp(-X. 2-Y. 2);
surf(X,Y,Z);
xlabel(X)
ylabel(Y)
zlabel(Z = X.*exp(-X. 2-Y. 2))
% A three-dimensional plot using the surfc command
x = [-2:0.2:2]; y = [-2:0.2:2];
[X,Y] = meshgrid(x,y);
Z=X.*exp(-X. 2-Y. 2);
surfc(X,Y,Z);
xlabel(X)
ylabel(Y)
zlabel(Z = X.*exp(-X. 2-Y. 2))
Please cite this article in press as: S.K. Sen, G.A. Shaykhian, MatLab tutorial for scientific and engineering computations, Nonlinear Analysis (2009),
doi:10.1016/j.na.2009.01.069
ARTICLE IN PRESS
S.K. Sen, G.A. Shaykhian / Nonlinear Analysis ( ) 13
% A three-dimensional plot using the contour command
x = [-2:0.2:2]; y = [-2:0.2:2];
[X,Y] = meshgrid(x,y);
Z=X.*exp(-X. 2-Y. 2);
contour(X,Y,Z);
xlabel(X)
ylabel(Y)
zlabel(Z = X.*exp(-X. 2-Y. 2))
% A three-dimensional plot using the surf command
x = [-2:0.2:2]; y = [-2:0.2:2];
[X,Y] = meshgrid(x,y);
Z = ((8*X+Y).*(cos(X)-... cos(2*Y)). 2)./(4*sqrt(0.8+(X-...
4.2). 2+2*(Y-7). 2))+Y;
surf(X,Y,Z);
xlabel(X)
ylabel(Y)
zlabel(Z )
% A three-dimensional plot using the surf command
x = [-2:0.2:2]; y = [-2:0.2:2];
[X,Y] = meshgrid(x,y);
Z = Z = (1-X). 2+100*(X. 2-Y). 2
surf(X,Y,Z);
xlabel(X)
ylabel(Y)
zlabel(Z )
13. Symbolic calculations
MATLAB is a numerical simulation tool (not a symbolic algebraic) MatLab provides a Symbolic Math toolbox to perform
symbolic calculations. Type the command help symbolic to get the MatLab symbolic capabilities. The Symbolic MathToolbox
uses symbolic objects produced by the sym function. For example, the statement
x = sym(x) produces a symbolic variable named x.
The statements x = sym(x); y = sym(y); can be combined into one statement involving the syms function.
syms x y.
Symbolic variables can be used in expressions or as arguments to many different functions. The command help symbolic
lists all MatLab Symbolic functions.
Please cite this article in press as: S.K. Sen, G.A. Shaykhian, MatLab tutorial for scientific and engineering computations, Nonlinear Analysis (2009),
doi:10.1016/j.na.2009.01.069
ARTICLE IN PRESS
14 S.K. Sen, G.A. Shaykhian / Nonlinear Analysis ( )
MatLab calculus symbolic functions
diff Differentiate
int Integrate
limit Limit
taylor Taylor series
jacobian Jacobian matrix
symsum Summation of series
Simplification (partial list)
simplify Simplify
expand Expand
factor Factor
collect Collect
simple Search for shortest form
numden Numerator and denominator
Integral transforms (partial list)
fourier Fourier transform
laplace Laplace transform
ztrans Z transform
ifourier Inverse Fourier transform
ilaplace Inverse Laplace transform
iztrans Inverse Z transform
Basic operations
sym Create symbolic object
syms Shortcut for constructing symbolic objects
findsym Determine symbolic variables
pretty Pretty print a symbolic expression
latex LaTeX representation of a symbolic expression
ccode C code representation of a symbolic expression
fortran FORTRAN representation of a symbolic expression
Linear algebra (partial list)
diag Create or extract diagonals
triu Upper triangle
tril Lower triangle
inv Matrix inverse
det Determinant
rank Rank
Solution of equations (partial list)
solve Symbolic solution of algebraic equations
dsolve Symbolic solution of differential equations
finverse Functional inverse
compose Functional composition
Conversions (partial list)
double Convert symbolic matrix to double
sym2poly Symbolic polynomial to coefficient
char Convert sym object to string
Special functions (partial list)
sinint Sine integral
cosint Cosine integral
String handling utilities
isvarname Check for a valid variable name (MATLAB Toolbox)
vectorize Vectorize a symbolic expression
Demonstrations
symintro Introduction to the Symbolic Toolbox
symcalcdemo Calculus demonstration
symlindemo Demonstrate symbolic linear algebra
symvpademo Demonstrate variable precision arithmetic
symrotdemo Study plane rotations
symeqndemo Demonstrate symbolic equation solving
Access to Maple. (Not available with Student Edition)
maple Access Maple kernel
Please cite this article in press as: S.K. Sen, G.A. Shaykhian, MatLab tutorial for scientific and engineering computations, Nonlinear Analysis (2009),
doi:10.1016/j.na.2009.01.069
ARTICLE IN PRESS
S.K. Sen, G.A. Shaykhian / Nonlinear Analysis ( ) 15
mfun Numeric evaluation of Maple functions
mfunlist List of functions for MFUN
mhelp Maple help
procread Install a Maple procedure (Requires Extended Toolbox)
Examples of symbolic calculations
simple Search for simplest form of a symbolic expression diff Differentiate
Steps to execute a symbolic calculation
Simplify f = cos(x)2 + sin(x)2
f = cos(x)2 + sin(x)2 (1) Usecommand symbols to declare
f = simple(f) the variables necessary to perform a
simple(f) symbolic calculation
simplify:
1 (2) Use a MatLab symbolic command
radsimp: Given f (x, y) = sin(xy) cos(2y), calculate
sin(x)2+cos(x)2 df (x, y)/dx
combine(trig):
1 syms x y % or we can use x = sym(x);
factor: y= sym(y);
sin(x)2+cos(x)2
expand: f 1 = sin(x*y)*cos(2*y);
sin(x)2+cos(x)2 diff(f1)
combine:
1 % differentiate with respect to symbol x
convert(exp): ans =
-1/4*(exp(i*x)-1/exp(i*x))2+(1/2*exp(i*x)+1/2/exp(i*x))2 cos(x*y)*y*cos(2*y)
convert(sincos):
sin(x)2+cos(x)2 Given f (x, y) = sin(xy) cos(2y), calculate
convert(tan): df (x, y)/dy
4*tan(1/2*x)2/(1+tan(1/2*x)2)2
+(1-tan(1/2*x)2)2/(1+tan(1/2*x)2)2
syms x y % or we can use x = sym(x);
collect(x): y= sym(y);
sin(x)2+cos(x)2
ans = f2 = sin(x*y)*cos(2*y);
1 diff(f2,y) % differentiate with % respect to
symbol y
ans =
cos(x*y)*x*cos(2*y)-2*sin(x*y)*sin(2*y)
symsum Symbolic Summation int Integrate
Compute the following sums: Perform the following integrals symbolically, and
for the indefinite integrals, check the results by
differentiating:
n

k=1
k3
syms k n
symsum(k3,k,1, n)

/2
0
cos x sin xdx
ans = int(cos(x)*sin(x),x, 0,pi/2)
1/4*(n+1)4-1/2*(n+1)3+1/4*(n+1)2 ans =
pretty(ans) 1/2
4 3 2
1/4 (n + 1) - 1/2 (n + 1) + 1/4 (n + 1)

cos x sin xdx

simplify(ans) int(cos(x)*sin(x),x)
ans = ans =
1/4*n4+1/2*n3+1/4*n2 1/2*sin(x)2

3e(x
2
)dx
Please cite this article in press as: S.K. Sen, G.A. Shaykhian, MatLab tutorial for scientific and engineering computations, Nonlinear Analysis (2009),
doi:10.1016/j.na.2009.01.069
ARTICLE IN PRESS
16 S.K. Sen, G.A. Shaykhian / Nonlinear Analysis ( )
Examples of symbolic calculations
f=3*exp(-x2);
int(f,-Inf,Inf)
ans =
3*pi(1/2)
14. Conclusions
We hope this short tutorial serves as an introduction to explore learning of MatLab. As discussed in the tutorial,
considerable details about a problem can be exploited through the use of a programming tool. MatLab is best suited for
scientists and engineers. It has hundreds of standard functions supporting systems of linear equations, eigenvalue and
eigenvector computations, matrix factoring, data analysis and much more. We briefly examined the MatLab graphical
capabilities to demonstrate the analysis of problem attributes and constraints. The visualization aspect of this problem-
solving approach provides real insight into internal problem mechanisms and the performance of the problem solution.
Further reading
[1] V. Lakshmikantham, S.K. Sen, Computational Error and Complexity in Science and Engineering, Elsevier, Amsterdam, 2005.
[2] E.V. Krishnamurthy, S.K. Sen, Introductory Theory of Computer Science, Affiliated East-West Press, New Delhi, 2004.
[3] Problem solving skills. http://www.athealth.com/Consumer/disorders/problemsolving.html.
[4] M. Zywno, Instructional technology, learning styles and academic achievement, in: Proceedings of the 2002 American Society for Engineering
Education Annual Conference & Exposition.
[5] R. Matuu, R. Prokop, User-friendly MATLABprogramfor control androbust stability analysis of systems withparametric uncertainties, in: Proceedings
of the 13th Mediterranean Conference on Control and Automation Limassol, Cyprus, 2729 June, 2005.
[6] B. Daku, K. Jeffrey, An interactive computer-based tutorial for MATLAB, in: 30th ASEE/IEEE Frontiers in Education Conference, 1821 October, 2000.
[7] M. Wirth, P. Kovesi, MATLAB as an Introductory Programming Language, Wiley Periodicals Inc., 2006.
[8] Teaching problem-solving skills, Prepared for the TRACE Workshop, Teaching Problem-Solving Skills, 17 June, 2003.
[9] S. Navaee, N. Das, Utilization of MATLAB in structural analysis, in: Proceedings of the 2002 ASEE/SEFI/TUB Colloquium.
[10] S. Sen, G. Shaykhian, Scope of various random number generators in ant system approach for TSP, in: Proceedings of the 2007 American Society for
Engineering Education Annual Conference & Exposition.
[11] D. Bailey, P. Borwein1, S. Plouffe, On the rapid computation of various polylogarithmic constants, 1991 Mathematics Subject Classification, 11A05
11Y16 68Q25.
Please cite this article in press as: S.K. Sen, G.A. Shaykhian, MatLab tutorial for scientific and engineering computations, Nonlinear Analysis (2009),
doi:10.1016/j.na.2009.01.069

You might also like