Tutorial 1

download Tutorial 1

of 16

Transcript of Tutorial 1

  • ARTICLE IN PRESSNonlinear Analysis ( )

    Contents lists available at ScienceDirect

    Nonlinear Analysis

    journal homepage: www.elsevier.com/locate/na

    MatLab tutorial for scientific and engineering computationsInternational 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 Statesb 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:MatLabSymbolic calculationsMatrix manipulationsGraphical functions

    a b s t r a c t

    The computing scenario over centuries/millenniums has been changing based on thetools/power of tools often innovative available to mankind. We discuss here in tutorialform various features of MatLab and their usage to solve problems. MatLab is one of themost widely used, very high level programming languages for scientific and engineeringcomputations. It is very user-friendly and needs practically no formal programmingknowledge. Presented here are MatLab programming aspects and not just the MatLabcommands for scientists and engineers who do not have formal programming training andalso have no significant time to spare for learning programming to solve their real worldproblems. Specifically provided are programs for visualization. Also, stated are the currentlimitations of theMatLab, which possibly can be taken care of byMathworks Inc. in a futureversion 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 exposethe 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: [email protected] (S.K. Sen), [email protected] (G.A. Shaykhian).

    0362-546X/$ see front matter. Published by Elsevier Ltddoi: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 PRESS2 S.K. Sen, G.A. Shaykhian / Nonlinear Analysis ( )

    2. Introducing MatLab

    MatLab is a mathematical computation tool which is available commercially. Other mathematical computation toolsinclude Maple, Mathematica and MathCad. MatLab is an abbreviation for MATrix LABoratory. MatLab is a numericalcomputation 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 environmentusing symbolic toolbox. Note: Computer algebra programs, such as MAPLE or MATHEMATICA provide support forcalculating 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 ofthe C++ programming language, or from the 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 interpreterprogramming language (command interface). MatLab is packaged with an editor and debugging functionality. Debugging isuseful 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 subsequentcalculations. Variable names are case sensitive and keywords cannot be used as variable names (use command iskeywordto list MatLab keywords; iskeyword returns a cell array containing the MatLab keywords). The MatLab command whoand whos provide useful information regarding variables. The command who lists the variables in the currentworkspaceand 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;whoYour variables are:Awhos

    Name Size Byte classA 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 separatorblank 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

  • ARTICLE IN PRESSS.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 promptc control-c to stop execution and return to promptq control-q to stop execution and exit MatLabOrder 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 keywordsas shown below: iskeywordans =breakcasecatchcontinueelseelseifendforfunctionglobalifotherwisepersistentreturnswitchtrywhile

    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 orcolumn) and matrix is considered as two-dimensional. Examples:Scalar 17+6ans = 23 A= 23+2ans = 25

    Row Vector There are different ways to declare a row vector; A row vector with 5 different elements is declared andinitialized 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 = aPlease 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 PRESS4 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.00003.7000 2.0000 5.00001.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-files2. Workspace In Workspace browser, variables may be viewed, manipulated, saved, and cleared3. Launch Pad Easy access to tools, demos and documentations4. Command History Keeps lines entered in CommandWindow, previously used variables or functions can be copies andexecuted 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 ofvariables hold Ctrl key, click on variables) to open the MatLab Array Editor. In Array Editor (variables are used similar toMicrosoft Excel) changes to dimension of the matrix or individual entries can be made. In Array Editor Exchange databetween 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 MatLabmatrix 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 PRESSS.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 9a = 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 92 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 63 5 7 3 71 8 9 1 9Please 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 PRESS6 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 62 4 6 3 5 73 5 7 1 8 9% select the first row of Matrix a and assign it to vectorb

    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 7a = 1 8 92 4 63 5 71 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 asingle column

    b = a(:,2)b =458

    To suppress the output of a MATLAB % Use... to continue definition of a matrixcalculation, the command must be ended in multiple lineswith a semicolon; the output of Matrix a issuppressed 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 up4 MATLAB command, when a command is too long.58

    Convert a matrix to a column vector use the MatLab colonoperator (:)>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 elmatElementary matriceszeros 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 PRESSS.K. Sen, G.A. Shaykhian / Nonlinear Analysis ( ) 7

    Basic array informationsize 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() functionzeros(N) function returns an N-by-N matrix of zeros ones(N) function returns an N-by-N matrix of oneszeros(M,N) returns an M-by-N matrix of zeros ones(M,N) returns an M-by-N matrix of onesInitialize 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 1MatLab size() function MatLab length() functionsize(X) returns the size of a matrix for M-by-N matrix X,returns the two-element row vector D = [M, N] containingthe number of rows and columns in the matrix. For N-Darrays, SIZE(X) returns a 1-by-N vector of dimensionlengths.

    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 Ex1 zeros, the number of elements of vector Ex1 is equal to the number of columns inmatrix b. b x1 = zeros(length(b),1)b = x1 =1 1 1 01 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 istransposed by placing the symbol after the matrix or vector to be transposed. Transpose the column vector Ex1, assign resultto vector Ex2.

    x1=[3;5;7;9] x2=x1x1 = x2 =3 3 5 7 9579

    MatLab repmat() function the repmat() functionreturns 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 anindexing expression.M = [1 2; 3 4; 5 6];

    a = [1 2;3 4;5 6] M(:, end)=[ ] % delete the column of matrix Ma = M =1 2 13 4 35 6 5Please 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 PRESS8 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 23 4 3 4 3 45 6 5 6 5 61 2 1 2 M(end, :) = [ ] % delete the last row of matrix M3 4 3 4 M =5 6 5 6 1 2

    3 4

    10. Matrix arithmetic operations

    MatLab matrix arithmetic operations are:

    A+BA-BA*B A.*BA\B A.\BA/B A./BA B A. BA 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 byadding the corresponding entries together. A + B adds A andB. A and B must have the same dimensions, unless one isscalar.

    -matrix subtraction is the operation of subtracting twomatrices by subtracting the corresponding entriestogether. A - B subtracts B from A. A and B must have thesame 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-Bans = ans =4 7 -2 -39 11 -3 -3

    * matrix multiplicationis the operation of multiplying twomatrices; an M L matrix A can be multiplied on the rightby an L N matrix B; the number of columns in the matrixon the left A must equal the number of rows in the matrix onthe right B, unless one is a scalar. A*B is the linear algebraicproduct of A and B.

    .* term-by-termmultiplication (array multiplication)A.*B is the entry-by-entry product of A and B. A and Bmust have the same dimensions, unless one is scalar.M= [1 2; 3 4]

    Note: A B 6= BA N=[3 5; 6 7]; K=M.*NM= [1 2 3; 4 5 6 ]; K =N = [2 3; 5 6; 2 7]; K =M*N 3 10K = 18 2818 3645 84

    Matrix divisionMatLab 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 equationsmust be consistent; a least squares solution is not computed..\ Array left division. A.\B is thematrix with entries B(i,j)/A(i,j). A and Bmust 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.). Warningmessages are produced if X does not exist or is not unique. Rectangular matrices A are allowed, but the equations must beconsistent; a least squares solution is not computed../ Array right division. A./B is thematrixwith entries A(i,j)/B(i,j). A and Bmust 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 Xto 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.B1 (B1 exists)In X = A\B (left division), division is defined if A is invertible. In which case, X = A1.B (A1 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 PRESSS.K. Sen, G.A. Shaykhian / Nonlinear Analysis ( ) 9

    Given linear systems of equations

    AEx = EbSolution (if exists) is defined by left division Ex = A/EbX2 + X3 = 53X1 + X3 = 6-X1 + X2 = 1A= 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 divisionx=1.00002.00003.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 doingso), however, in which case they lose their initial intended meanings. The MatLab standard functions are grouped bytheir functions; for example, Trigonometric Functions, Exponential Functions, Complex Functions, Rounding and remainderfunctions. 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 logarithmcosh Hyperbolic cosine log10 Common (base 10) logarithmcot Cotangent sqrt Square rootComplex Functions (partial list) Rounding and remainder functions (partial list)angle Phase angle ceil Round toward plus infinityconj Complex conjugate fix Round toward zeroimag Complex imaginary part floor Round toward minus infinityisreal True for noncomplex arraysStatistical 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

    xmin smallest component factorial(x) returns factorial of xmax largest component primes(x) generates a list of prime numbers less than or

    equal to xvar variance of the elements in a vector isprime(x) returns 1 if the elements of x which are prime, 0

    otherwisecov 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 graphicalfunctions (partial list)

    plot Linear plot (2D) plot3 Plot lines and points in 3-Dspace

    loglog Loglog scale plot mesh 3-D mesh surfacesemilogx Semi-log scale plot surf 3-D colored surfacesemilogy Semi-log scale plot fill3 Filled 3-D polygonsPlease 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 PRESS10 S.K. Sen, G.A. Shaykhian / Nonlinear Analysis ( )

    polar Polar coordinate plot. axis Control axis scaling andappearance

    plotyy Graphs with y tick labels on the leftand right

    zoom Zoom in and out on a 2-D plot

    bar for a vertical bar graph grid Grid linesbarh for a horizontal bar graphstem for a stem plot

    box Axis boxhold Hold current graphaxes Create axes in arbitrary position

    Examples plot() function is used to plot a two-dimensional plot Color types Symbols Lineb blue solid . point -g green dotted o circle :r red dashdot x x-mark -.c cyan dashed + plus - -m magenta * stary yellow s squarek black d diamond

    v triangle (down) triangle (up)< triangle (left)> triangle (right)p pentagramh hexagram

    plot3() function is used to plot a three-dimensional plotA plot can be made using various symbols, colors and line typesLine types, plot symbols and colors for plot() or plot3() functions arerepresented through a character stringFor example, a character string go: means a green dotted line with acircle at each data pointplot(X,Y,go:) plots a green dotted line with a circle at each data pointplot3(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 ateach 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 PRESSS.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 plotsangle = 0:pi/30:2*pif1 = 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 pointsbetween 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 PRESS12 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)); % functionvaluemesh(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 PRESSS.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 SymbolicMath toolbox to performsymbolic calculations. Type the commandhelp symbolic to get theMatLab symbolic capabilities. The SymbolicMath Toolboxuses 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 symboliclists 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 PRESS14 S.K. Sen, G.A. Shaykhian / Nonlinear Analysis ( )

    MatLab calculus symbolic functionsdiff Differentiateint Integratelimit Limittaylor Taylor seriesjacobian Jacobian matrixsymsum Summation of seriesSimplification (partial list)simplify Simplifyexpand Expandfactor Factorcollect Collectsimple Search for shortest formnumden Numerator and denominatorIntegral transforms (partial list)fourier Fourier transformlaplace Laplace transformztrans Z transformifourier Inverse Fourier transformilaplace Inverse Laplace transformiztrans Inverse Z transformBasic operationssym Create symbolic objectsyms Shortcut for constructing symbolic objectsfindsym Determine symbolic variablespretty Pretty print a symbolic expressionlatex LaTeX representation of a symbolic expressionccode C code representation of a symbolic expressionfortran FORTRAN representation of a symbolic expressionLinear algebra (partial list)diag Create or extract diagonalstriu Upper triangletril Lower triangleinv Matrix inversedet Determinantrank RankSolution of equations (partial list)solve Symbolic solution of algebraic equationsdsolve Symbolic solution of differential equationsfinverse Functional inversecompose Functional compositionConversions (partial list)double Convert symbolic matrix to doublesym2poly Symbolic polynomial to coefficientchar Convert sym object to stringSpecial functions (partial list)sinint Sine integralcosint Cosine integralString handling utilitiesisvarname Check for a valid variable name (MATLAB Toolbox)vectorize Vectorize a symbolic expressionDemonstrationssymintro Introduction to the Symbolic Toolboxsymcalcdemo Calculus demonstrationsymlindemo Demonstrate symbolic linear algebrasymvpademo Demonstrate variable precision arithmeticsymrotdemo Study plane rotationssymeqndemo Demonstrate symbolic equation solvingAccess 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 PRESSS.K. Sen, G.A. Shaykhian / Nonlinear Analysis ( ) 15

    mfun Numeric evaluation of Maple functionsmfunlist List of functions for MFUNmhelp Maple helpprocread Install a Maple procedure (Requires Extended Toolbox)

    Examples of symbolic calculations

    simple Search for simplest form of a symbolic expression diff DifferentiateSteps 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 calculationsimplify:1 (2) Use a MatLab symbolic commandradsimp: Given f (x, y) = sin(xy) cos(2y), calculatesin(x)2+cos(x)2 df (x, y)/dxcombine(trig):1 syms x y % or we can use x = sym(x);factor: y= sym(y);sin(x)2+cos(x)2expand: f 1 = sin(x*y)*cos(2*y);sin(x)2+cos(x)2 diff(f1)combine:1 % differentiate with respect to symbol xconvert(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), calculateconvert(tan): df (x, y)/dy4*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)2ans = f2 = sin(x*y)*cos(2*y);1 diff(f2,y) % differentiate with % respect to

    symbol yans =cos(x*y)*x*cos(2*y)-2*sin(x*y)*sin(2*y)

    symsum Symbolic Summation int IntegrateCompute the following sums: Perform the following integrals symbolically, and

    for the indefinite integrals, check the results bydifferentiating:

    nk=1k3

    syms k n symsum(k3,k,1, n) pi/20 cos x sin xdxans = 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 21/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(x2)dxPlease 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 PRESS16 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 forscientists and engineers. It has hundreds of standard functions supporting systems of linear equations, eigenvalue andeigenvector computations, matrix factoring, data analysis and much more. We briefly examined the MatLab graphicalcapabilities 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 EngineeringEducation Annual Conference & Exposition.

    [5] R.Matuu, R. Prokop, User-friendlyMATLABprogram for control and robust stability analysis of systemswith parametric uncertainties, in: Proceedingsof 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

    MatLab tutorial for scientific and engineering computationsIntroductionIntroducing MatLabMatLab operators and notationsMatLab keywordsScalar, vector and matrix in MatLabGetting startedArray editorWork with matrixElementary matrix manipulationsMatrix arithmetic operationsMatLab mathematical functionsMatLab graphical functionsSymbolic calculationsConclusionsFurther reading