0% found this document useful (0 votes)
60 views63 pages

Matlab Training Manual-1-63

Uploaded by

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

Matlab Training Manual-1-63

Uploaded by

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

Basic MATLAB

By:
Dr. Yengkhom Satyendra Singh
CONTENTS

1. INTRODUCTION 1
1.1 Starting MATLAB 1
1.2 Working with the Command Window 3
1.3 Arithmetic Operation 5
1.4 Defining Scalar Variables 6
1.5 Elementary Math Built-in Functions 8

2. ARRAYS, VECTORS AND MATRICES 11


2.1 One-Dimensional Array (Vector) 11
2.2 Two-Dimensional Array (Matrix) 13
2.3 Transpose Operator 14
2.4 Special Matrices (the zeros, ones, eye and rand Commands) 14
2.5 Array Addressing 15
2.6 Deleting Elements from Existing Matrix 18
2.7 Built-in Functions for Handling Array (Vector and Matrix) 18
2.8 String and String as Variables 19
2.9 Mathematical Operations with Arrays (Addition, Subtraction and Multiplication) 20
2.10 Element-by-Element Operations 21
2.11 Inverse of a Matrix 23
2.12 Determinant 23
2.13 Eigenvalues and Eigenvectors 24

3. SCRIPT 25
3.1 Creating and saving a Script File 25
3.2 Running (Executing) a Script File 27
3.3 Current Folder 27
3.4 The input command 28
3.5 The output commands 28
3.6 Importing and Exporting Data 31

4. LOOPS AND CONDITIONAL STATEMENT 34


4.1 Relational and Logical Operators 34

i
4.2 Loops 36
4.2.1 for-end Loop 36
4.2.2 while-end Loop 38
4.3 Conditional Statements 39
4.3.1 if-else-end Structure 39
4.3.2 if-elseif-else-end Structure 40
4.4 The switch-case Structure 42
4.5 Nested Loops and Conditional Statements 43
4.6 The break and continue Commands 44
4.6.1 The break Command 44
4.6.2 The continue Command 44

5. FUNCTIONS AND PLOTS 46


5.1 Functions 46
5.2 inline Functions 48
5.3 Two-Dimensional Plots 49
5.4 Plotting Multiple Graphs 53
5.5 Formatting a Plot 54
5.6 Three-Dimensional Plots 57

6. POLYNOMIALS, DIFFERENTIATION AND INTEGRATION 61


6.1 Polynomials 61
6.1.1 Roots of a Polynomial 61
6.1.2 Value of a Polynomial 62
6.1.3 Addition, Multiplication and Division of a Polynomials 63
6.1.4 Derivative of Polynomials 64

7. SYMBOLIC MATHS 66
7.1 Symbolic Objects and Symbolic Expressions 66
7.1.1 Creating Symbolic Objects 66
7.1.2 Creating Symbolic Expressions 67
7.1.3 The findsym command 69
7.2 Manipulating Symbolic Expression 69
7.2.1 The collect , expand and factor commands 69
7.2.2 The simplify , numden and pretty commands 71
7.3 Solving Algebraic Equations 72
7.4 Calculating Limits 74
7.5 Computing Derivatives 75
7.6 Computing Integration 77

ii
1 INTRODUCTION

MATLAB is an interactive high-performance language for technical computing. It originated in


the middle of the 1980s and stands for MATrix LABoratory. It integrates numerical
computation, visualization, and programming in an easy-to-use environment where problems and
solutions are expressed in familiar mathematical notation.

MATLAB is good for the following: Computations, including linear algebra, data analysis,
signal processing, polynomials and interpolation, numerical integration (quadrature), and
numerical solution of differential equations. It has powerful graphic tools and can produce nice
pictures in both 2D and 3D, including color, lighting, and animation. It also has collections of
specialized functions, called toolboxes, which extend its functionality. Ex: Excel link allows data
to be written in a format recognized by Excel, Statistics Toolbox allows more specialized
statistical manipulation of data (Anova, Basic Fits, etc), Neural Network toolbox allows data
fitting, pattern recognition, clustering, time series prediction and modeling. Typical uses include:

• Math and computation


• Algorithm development
• Modeling, simulation, and prototyping
• Data analysis, exploration, and visualization
• Scientific and engineering graphics
• Application development, including Graphical User Interface building

1.1 Starting MATLAB


When we open MATLAB, we will see a main window entitled MATLAB as shown in Figure
1.1. The MATLAB window contains four windows that are displayed under the Toolstrip: the
Command Window (larger window at the center), the Current Folder Window (on the left), the
Workspace Window and Command History Window (on the right). These windows are four of
the eight windows in MATLAB. A List of various windows and their purpose are given in Table
1.1. A start button on the lower left corner can be used to access MATLAB tools and features.
Table 1.1. Eight Different windows in MATLAB.

Window Purpose
Command Window Main Window enters variables, run programs.
Figure Window Contains output from graphic commands.

1
Editor Window Creates and debugs script and function files.
Help Window Provides help information.
Launch Pad Window Provides access to tools, demos, and documentation.
Command History Window Logs commands entered in the command Window.
Workspace Window Provides information about the variables that are used.
Current Directory Window Shows the files in the current Directory.

Figure1.1. The default view of MATLAB desktop.

Among the eight different windows in MATLAB four windows that will come across frequently
are Command Window, Figure Window, Help Window and the Script Window.

Figure 1.2. An Editor Window.

Command Window: The Command Window is MATLAB's main window and opens when
MATLAB is started. It is convenient to have the Command Window as the only visible window.
This can be done either by closing all the other windows, or by selecting Command Window

2
only in the menu that opens when the Layout icon on the toolstrip is selected. To close a
window, click on the pull-down menu at the top right-hand side of the window and then select
Close.

Editor Window: The Editor Window is used for writing and editing programs. This window
opens by clicking on the New Script icon in the toolstrip, or by clicking on the New icon and
then selecting Script from the menu that opens. An example of an Editor Window is shown in
Figure 1.2.

Help Window: The Help Window contains help information. This window can be opened from
the Help icon in the toolstrip of the Command Window or the toolbar of any MATLAB window.
The Help Window is interactive and can be used to obtain information on any feature of
MATLAB.

Figure Window: A figure window opens automatically when graphics commands are executed,
and contains graphs created by these commands. An example of a figure window is displayed in
Figure 1.3.

Figure 1.3. A Figure Window.

1.2 Working with the Command Window


Command windows can be used for executing commands, opening other windows, running
programs written by the user and managing the software. The MATLAB prompt on the
command window consists of two adjacent right angle brackets, i.e. ,

>>

When the command window is active, a blinking cursor appears to the right of the prompt.

>>|

3
This signifies that MATLAB is waiting to perform a mathematical operation. Once a command
is typed and the Enter key is pressed, the command is executed and the output is displayed.

≫4+6
ans =
10

Several commands can be typed in the same line. This is done by typing a comma between the
commands. When an enter key is pressed it is executed from left to right.

≫ 4 ∗ 5, 19 + 6 − 3/2,8 ∗ 9 + 2
ans =
20
ans =
23.5000
ans =
74

If a semicolon is typed at the end of the command the output is suppressed.

≫ 4 + 6;

Table 1.2. Commands for managing session on Command Window.

Commands Purpose
clc Clears Command Window.
clear Removes all variables from memory.
help Lists all primary help topics.
quit or exit Terminates MATLAB.
who Display a list of the variables currently in the memory.
whos Display a list of variables currently in the memory with their size, bytes and class.

Table 1.3. Commonly used special character.

Syntax Description
[] Brackets are used to form vectors and matrices.
() Parentheses are used to indicate precedence in arithmetic expressions,
encloses function arguments and array indices.
= Used in assignment statement. B = A stores the elements of A in B. == is the
relational equals operator.
: Generates regularly spaced elements and represents an entire row or column.
… Line continuation operator.
, Separates statements and elements in a row.
; Separates columns and suppresses display.
% Percent denotes a comment.

1.3 Arithmetic Operation

4
Basic arithmetic operations offers by MATLAB are:
Table 1.4. Arithmetic Operators.

Operation Symbol Example


Addition + >> 7+5
ans =
12
Subtraction - >> 5-2
ans =
3
Multiplication * >> 5*6
ans =
30
Right Division / >> 6/2
ans =
3
Left Division \ >> 2\6
ans =
3
Exponentiation ^ >> 3^2
ans =
9

The simplest way of using MATLAB is as a scientific calculator. This is done in the Command
Window by typing a mathematical expression and pressing the enter key. MATLAB executes the
expression that has several operations according to the order of precedence displayed below:
Table 1.5. Order of precedence.

Precedence Mathematical Operation


First Parentheses. For nested parentheses, the innermost are executed first.
Second Exponentiation.
Third Multiplication and division.
Fourth Addition and Subtraction.

Example:

>> 5+4-7/3 % 7/3 is executed first and then executed from left to right.
ans =
6.6667
>> 4*5+7^2 % 7^2 is executed first
ans =
69
>> 2-7*5+43/9^2+28+6*4
ans =
19.5309
>> 25+14/2+9*(7-6/2+3^2)+4/2 % parentheses is executed first.
ans =
151

5
1.4 Defining Scalar Variables
A variable is a name made of a letter or a combination of several letters (and digits) that is
assigned a numerical value. Once a variable is assigned a numerical value, it can be used in
mathematical expressions, in functions, and in any MATLAB statements and commands. A
variable is actually a name of a memory location and the assigned value is stored in that memory
location. If the variable is assigned a new value the content of the memory location is replaced.

Assignment operator ‘=’assigns a value to a variable. The format for defining a variable is,

Variable_name = A numerical value or a computable expression.

Variable naming rules in MATLAB are:

• Variable names are case-sensitive. Eg:- cost, Cost COST…… are all treated as different
variables.
• Variable names can contain upto 63 (in MATLAB 7) characters long. To see how many
characters MATLAB support type var_name=namelengthmax in the command
window.
• Variable name must start with a letter, followed by any number of letters, digits, or
underscores. Eg:- Variable_name, r234yt, copy_23.
• Avoid using the names of a built-in function for a variable (avoid using cos, sin, exp, sqrt,
etc…)

Example:

>> a = 4 % a variable ‘a’ is define and assigned a value 4.


a=
4
>> x = 2*a+14-a % a variable x is define and an expression is assigned to it.
x=
18

We can type several assignments on the same line by separating them with commas or
semicolons. If we separate them with commas, it will be displayed, and if you used the
semicolon, it will not. For example,

>> a = 4, A = 6; v=-2
a=
4
v=
-2

6
Complex values can be assigned to variables. The imaginary unit √−1 is preassigned to the
variable i. MATLAB also allow the symbol j to be used to represent the imaginary unit for input.
However it always uses an i for display. For Example,

>> x = 2+ i*8
x=
2.0000 + 8.0000 i
>> x = 3 + j*9
x=
3.0000 + 9.0000 i

There are several predefined variables, for example pi.

>> pi
ans =
3.1416

We notice that MATLAB displayed four decimal places. If we desire additional precision, type
the following:

>> format long


>> pi
ans =
3.141592653589793 % display pi value upto 15 decimal digits
>> format short % Return to the four decimal place.

MATLAB has several other formats for displaying numbers. The command for typing format is,

format style

The style of the format controls the output display format for numbers. Details of these
formats can be obtained by typing help format in the Command Window.
Table 1.6: Numeric format.

Style Description Examples


short (default) Fixed-decimal format with 4 digits after the decimal >> format short
point. >> pi
ans =
3.1416
long Fixed-decimal format with 15 digits after the >> format long
decimal point. >> pi
ans =
3.141592653589793
short e Short scientific notation with 4 digits after the >> format short e
decimal point. >> pi
ans =
3.1416e+000
long e Scientific notation with 15 digits after the decimal >> format long e
point. >> x=2/3

7
x=
6.666666666666666e-001
rat or rational Display rational number. >> format rat
>> x=8/7
x=
8/7

1.5 Elementary Math Built-in Functions


A function has a name and an argument in parentheses as function_name(argument).
Example, the function that calculates the square root of a number is sqrt(x). Here name of the
function is sqrt and the argument is x. Argument can be number, a variable that has been
assigned a numerical value or a computable expression that can be made up of numbers and/ or
variables. Functions can also be included in arguments, as well as in expressions. Example :

>> sqrt(64) % argument is a number.


ans =
8
>> sqrt(50+14*3) % argument is an expression.
ans =
9.5917
>> sqrt(54+9*sqrt(100)) % argument includes a function.
ans =
12
>> x = 93;
>> sqrt(x) % argument is a variable.
ans =
9.6437

Details of MATLAB built-in functions can be obtained from MATLAB by typing help
elfun in the Command Window. Some built-in functions are given below:

Table 1.7: Some built-in functions in MATLAB.

Function Description Examples


sin(x) returns the sine of x >> sin(pi/2)
ans =
1
sind(x) returns the degree of sin of x >> sind(30)
ans =
0.5000
cos(x) returns the cosine of x >> cos(pi/6)
ans =
0.8660
tan(x) returns the tangent of x >> tan(pi/4)
ans =
1.0000
atan(x) returns the inverse tangent of x >> atan(1)
ans =

8
0.7854
atand(x) returns the degree of inverse tangent of x >> asind(1)
ans =
90
acos(x) returns the inverse cosine of x >> acos(1)
ans =
0
asin(x) returns the inverse sine of x >> asin(1)
ans =
1.5708
exp(x) returns ex >> exp(5)
ans =
148.4132
log(x) returns the natural logarithm of x >> log(1)
ans =
0
log10(x) returns the log10(x) >> log10(16)
ans =
1.2041
sqrt(x) returns the square root of x >> sqrt(9)
ans =
3
abs(x) returns the absolute value of x >> abs(-5.98)
ans =
5.9800
round(x) returns the integer closest to x >> x=9.62
x=
9.6200
>> round(x)
ans =
10
>> y=5.12
y=
5.1200
>> round(y)
ans =
5
ceil(x) returns the smallest integer greater than or equal to x >> y=3.89
y=
3.8900
>> ceil(y)
ans =
4
>> x=3.122
x=
3.1220
>> ceil(x)
ans =
4
>> p=-2.899;
>> q=-3.11;
>> ceil(p)
ans =
-2
>> ceil(q)

9
ans =
-3
floor(x) returns the largest integer less than or equal to x >> p=-2.899
p=
-2.8990
>> floor(p)
ans =
-3
>> q=-3.11
q=
-3.1100
>> floor(q)
ans =
-4

>> ceil(p)

ans =

-2

>> ceil(q)

ans =

-3
isprime(n) returns true if n is prime >> isprime(12)
ans =
0
> isprime(29)
ans =
1
factor(k) returns prime factors of k >> factor(45)
ans =
3 3 5
sign(x) returns the sign (1 or −1) of x; sign(0) is 0 >> sign(7)
ans =
1
>> sign(-8)
ans =
-1

10
2 ARRAYS, VECTORS AND MATRICES

An array is a list of numbers arranged in rows and/ or columns. The simplest array (one-
dimensional) is a row, or a column of numbers called vectors. A more complex array (two
dimensional) is a collection of numbers arranged in rows and columns called matrix.

2.1 One-Dimensional Array (Vector)


The vectors are created by typing the elements (numbers) inside the square brackets [].

Row vector: To create a row vector type the elements with a space or a comma between the
elements inside the square brackets.

>> X = [2 4 6 8] % Elements separated by space.


X=
2 4 6 8
>> Y = [4, 3, 5, 2, 81] % Elements separated by comma.
Y=
4 3 5 2 81

Column vector: To create a column vector type the left square bracket [ and then enter the
elements with a semicolon between them, or press the Enter Key after each element. Type the
right square ] bracket after the last element.

>> Z = [127; 130; 136; 145; 158; 178; 211] % Elements separated by semicolon.
Z=
127
130
136
145
158
178
211
>> U=[45 % After each element enter key is pressed except the last element.
98
103
39]

U=

11
45
98
103
39

Creating a vector with constant spacing by specifying the first term, the spacing, and the last
term. For a vector with constant spacing the differences between the elements is the same.

Example:

>> v = [2:2:10] % 1st term is 2, spacing is 2 and last term is 10


v=
2 4 6 8 10

A vector in which the first term is m, the spacing is q and the last term is n is created by typing

Variable_name=[m:q:n] or m:q:n

Example:

>> u=1:4:17
u=
1 5 9 13 17
>> x=1:3:15
x=
1 4 7 10 13
>> y=2:9 % 1st term is 2, last term is 9. If spacing is not given by default
% MATLAB take the spacing as 1.
y=
2 3 4 5 6 7 8 9
>> z= 21:-3:6 % 1st term is 21, spacing is -3 and last term is 6.
z=
21 18 15 12 9 6

Creating a vector with linear (equal) spacing by specifying the first and last terms, and the
number of terms: A vector with n elements that are linearly (equally) spaced in which the first
element is xinitial and the last element is xfinal can be created by typing the linspace
command (MATLAB determines the correct spacing):

Variable_name=linspace(xinitial, xfinal, n)

Example:

>> v1=linspace(0,8,6)
v1 =
0 1.6000 3.2000 4.8000 6.4000 8.0000
>> v2=linspace(30,10,11)
v2 =

12
30 28 26 24 22 20 18 16 14 12 10
>> v3=linspace(49.5,0.5) % here only the first term and last term are given,
% by default MATLAB take number of terms as 100.
v3 =
Columns 1 through 9
49.5000 49.0051 48.5101 48.0152 47.5202 47.0253 46.5303 46.0354 45.5404
…………………..
Columns 91 through 99
4.9545 4.4596 3.9646 3.4697 2.9747 2.4798 1.9848 1.4899 0.9949
Column 100
0.5000

2.2 Two-Dimensional Array (Matrix)


A matrix is a rectangular array of numbers. Matrices can be used to store information like in a
table. Matrices play an important role in linear algebra and are used in science and engineering to
describe many physical quantities. A matrix is created by assigning the elements of the matrix to
a variable. This is done by typing the elements, row by row, inside square bracket []. First type
the left bracket [, then type the first row separating the elements with spaces or commas. To type
the next row type a semicolon or press Enter. Type the right bracket ] at the end of the last row.

Variable_name=[1st row element; 2nd row element; 3rd row element;……….; last row
element]

The elements that are entered can be numbers or mathematical expressions that may include
numbers, predefined variables, and functions. All the rows must have the same number of
elements.

>> a=[5 35 43; 2 19 7; 22 37 12] % Semicolon is used to separate each row.


a=
5 35 43
2 19 7
22 37 12
>> b=[2 -5 19 % Enter key is press after each row.
3 8 19
8 14 11]
b=
2 -5 19
3 8 19
8 14 11
>> cd=6;e=3;h=4;
>> Mat=[e, cd*h, cos(pi/3); h^2, sqrt(h*h/cd), 14] % Elements are define by
% mathematical expression
Mat =
3.0000 24.0000 0.5000
16.0000 1.6330 14.0000
>> A=[1:2:11; 0:5:25; linspace(10,60,6); 67 2 43 68 4 13] % Rows of the matrix
% are created using the definition for creating vectors.

13
A=
1 3 5 7 9 11
0 5 10 15 20 25
10 20 30 40 50 60
67 2 43 68 4 13

2.3 Transpose Operator


The transpose operator, when applied to a vector, switches a row (column) vector to a column
(row) vector. When applied to a matrix, it switches the rows (columns) to columns (rows). The
transpose operator is applied by typing a single quote ‘ ′’ following the variable to be transposed.

>> a=[12 7 82 35 10]'


a=
12
7
82
35
10
>> a'
ans =
12 7 82 35 10
>> b=[2 -1 9; 6 11 19]
b=
2 -1 9
6 11 19
>> b'
ans =
2 6
-1 11
9 19

2.4 Special Matrices (the zeros, ones, eye and rand Commands)
The zeros(m, n), ones(m, n), and eye(n) commands can be used to create matrices
that have elements with special values. The zeros(m, n) and the ones(m, n) commands
create a matrix with m rows and n columns in which all elements are the numbers 0 and 1,
respectively. The eye(n) command creates a square matrix with n rows and n columns in
which the diagonal elements are equal to 1 and the rest of the elements are 0.

>> zeros(2,3)
ans =
0 0 0
0 0 0
>> zeros(4)
ans =
0 0 0 0

14
0 0 0 0
0 0 0 0
0 0 0 0
>> ones(3,4)
ans =
1 1 1 1
1 1 1 1
1 1 1 1
>> ones(3)
ans =
1 1 1
1 1 1
1 1 1
>> eye(3)
ans =
1 0 0
0 1 0
0 0 1
>> eye(3,4)
ans =
1 0 0 0
0 1 0 0
0 0 1 0

The rand command generates uniformly distributed numbers with values between 0 and 1.

The following is the list of rand command:

Table 2.1. List of rand commands.

Command Description Example


Rand Generates a single random number between 0 and 1. >> rand
ans =
0.9058
rand(1,n) Generates an n element row vector of random >> rand(1,3)
numbers between 0 and 1. ans =
0.6557 0.0357 0.8491
rand(n) Generates an nxn matrix with random numbers >> rand(3)
between 0 and 1. ans =
0.1270 0.0975 0.9575
0.9134 0.2785 0.9649
0.6324 0.5469 0.1576
rand(m,n) Generates an mxn matrix with random numbers >> rand(2,3)
between 0 and 1. ans =
0.9706 0.4854 0.1419
0.9572 0.8003 0.4218
randperm(n) Generates a row vector with n elements that are >> randperm(3)
random permutation of integers 1 through n. ans =
2 1 3

2.5 Array Addressing


15
Elements in an array can be addressed individually or in subgroups.

Array Addressing in vectors: The address of an element in a vector is its position in the row (or
column). If d is a vector, then we can refer the element at n position by typing d(n).

>> d=[12:4:40]
d=
12 16 20 24 28 32 36 40
>> d(1) % 1 refers the element position in d which is the first element of vector d.
ans =
12
>> d(6) % 6 refers the 6th element of vector d.
ans =
32

Array Addressing in Matrices: The address of an element in a matrix is its position, defined by
the row number and the column number where it is located. Individual elements and columns in
a matrix can be referenced using MATLAB.

Consider the matrix:

>> A=[2 44 81; 19 76 34; 23 11 63]


A=
2 44 81
19 76 34
23 11 63

We can refer the element at row position m and at column position n by typing A(m,n).

>> A(2,3)
ans =
34

A colon can be used to address a range of elements in a vector or matrix. In a vector, d(:)
refers to all the elements of the vector d.

>> d(:)
ans =
12
16
20
24
28
32
36
40

d(m,n) refers to elements m through n of the vector.


16
>> d(3:6) % refers elements 3 through 6 of d.
ans =
20 24 28 32

For matrix, to reference all elements in the ith row of matrix V we write as V(i , :), on the
other hand, to reference all elements in the jth column we write as V(: , j).

>> V=[2 7 -1 9 13; 3 14 7 -8 6; 73 30 18 22 4;17 5 -4 92 3]


V=
2 7 -1 9 13
3 14 7 -8 6
73 30 18 22 4
17 5 -4 92 3
>> V(3,:)
ans =
73 30 18 22 4
>> V(:,4)
ans =
9
-8
22
92

To refer all elements in all rows between columns m and n of V we write V(: , m:n).

>> V(:,3:5)
ans =
-1 9 13
7 -8 6
18 22 4
-4 92 3

To refer all elements in all columns between rows p and q of V we write V(p:q ,:).

>> V(2:4,:)
ans =
3 14 7 -8 6
73 30 18 22 4
17 5 -4 92 3

To refer to the elements in rows p through q and column m through n of V we write V(p:q,m:n).

>> V(2:4,3:5)
ans =
7 -8 6
18 22 4
-4 92 3

17
2.6 Deleting Elements from Existing Matrix

An element or a range of elements, of an existing variable can be deleted by reassigning nothing


to these elements using square brackets []. This can be used to delete a row or column in a
matrix. By deleting elements a vector can be made to have a smaller size. Examples are:

>> a=[3 5 19 -4 23 8 61 22 14];


>> a(6)=[] % Eliminate the 6th element.
a=
3 5 19 -4 23 61 22 14
>> a(2:4)=[] % Eliminate elements 2 through 4.
a=
3 23 61 22 14
>> A=[10 4 16 18; 2 5 9 17;71 22 39 8;23 41 55 12]
A=
10 4 16 18
2 5 9 17
71 22 39 8
23 41 55 12
>> A(3,:)=[] % Eliminate the 3rd row.
A=
10 4 16 18
2 5 9 17
23 41 55 12
>> A(:,4)=[] % Eliminate the 4th column.
A=
10 4 16
2 5 9
23 41 55

2.7 Built-in Functions for Handling Array (Vector and Matrix)

MATLAB has many built-in functions for managing and handling arrays. Some of these are
listed below:

Table 2.2. Some of the Built-in Functions for handling arrays in MATLAB.

Function Description Example


length(a) Returns the number of elements in a=
the vector a. 3 23 61 22 14

18
>> length(a)
ans =
5
size(A) If A is an [m,n] matrix, returns the A=
size mxn of the A. 10 4 16
2 5 9
23 41 55
>> size(A)
ans =
3 3
diag(A) When A is a matrix, creates a vector A=
from the diagonal of A. 10 4 16
2 5 9
23 41 55
>> diag(A)
ans =
10
5
55
mean(A) If A is a vector, returns the mean a=
value of the elements of the vector. 3 23 61 22 14
>> mean(a)
ans =
24.6000

2.8 String and String as Variables


A string is an array of characters. It is created by typing the characters within single quotes.
Strings can include letters, digits, other symbols and spaces. Example:

>>u='den 5'
u=
den 5
>> v='3%_87 fo'
v=
3%_87 fo
>> p='Training'
p=
Training

When a variable is defined as a string, the characters of the string are stored in an array just as
numbers are. Each character including a space, is an element in the array. The elements of the
vectors are addressed by their position. Examples,

>> length(u)
ans =
5
>> p(6)
ans =
i

19
MATLAB has a built-in function name char that creates an array with rows that have the same
number of characters from an input of rows that are not of the same length. MATLAB makes the
length o all the rows equal to the longest row by adding spaces at the end of the short lines. In the
char function, the rows are entered as strings separated by a comma according to the following
format. Format of char function is,

variable_name=char(‘string1’, ‘string2’, ‘string3’)

Example:

>> Info=char('Student Name:', 'John Smith', 'Grade', 'A-')


Info =
Student Name:
John Smith
Grade
A-

2.9 Mathematical Operations with Arrays (Addition, Subtraction and


Multiplication)
Arithmetic Operations with Scalar: Multiplying a matrix by a scalar simply multiplies each
element of the matrix by the number. The same holds for division, addition, and subtraction.

A=
21 7 -6
9 45 23
92 6 43
>> c=3;
>> c*A
ans =
63 21 -18
27 135 69
276 18 129
>> c+A
ans =
24 10 -3
12 48 26
95 9 46
>> A/c
ans =
7.0000 2.3333 -2.0000
3.0000 15.0000 7.6667
30.6667 2.0000 14.3333

Addition and Subtraction: The operation + (addition) and – (subtraction) can be used with arrays
of identical size. The sum or the difference of two arrays is obtained by adding or subtracting,
their corresponding elements.

20
A=
21 7
9 45
92 6
>> B
B=
73 92
41 54
8 37
>> A+B
ans =
94 99
50 99
100 43
>> A-B
ans =
-52 -85
-32 -9
84 -31

Multiplication: Array multiplication (*) can be operated according to linear algebra. Example:

A=
21 7 6
9 45 12
92 6 4
>> B
B=
73 92
41 54
8 37
>> A*B
ans =
1868 2532
2598 3702
6994 8936

2.10 Element–by–Element Operations


Element –by –element multiplication, division and exponentiation of two vectors or matrices is
entered in MATLAB by typing a period in front of the arithmetic operator.
Table 2.3. Element-by-element operators.

Symbol Description
.* Multiplication
.^ Exponentiation
./ Right Division
.\ Left Division

21
Element-by-element multiplication, division and exponentiation of two vectors gives:

𝑎𝑎 = [𝑎𝑎1 𝑎𝑎2 𝑎𝑎3 𝑎𝑎4 ], 𝑏𝑏 = [𝑏𝑏1 𝑏𝑏2 𝑏𝑏3 𝑏𝑏4 ]

𝑎𝑎.∗ 𝑏𝑏 = [𝑎𝑎1 𝑏𝑏1 𝑎𝑎2 𝑏𝑏2 𝑎𝑎3 𝑏𝑏3 𝑎𝑎4 𝑏𝑏4 ]

𝑎𝑎./𝑏𝑏 = [𝑎𝑎1 /𝑏𝑏1 𝑎𝑎2 /𝑏𝑏2 𝑎𝑎3 /𝑏𝑏3 𝑎𝑎4 /𝑏𝑏4 ]

𝑎𝑎. ^𝑏𝑏 = [𝑎𝑎1 ^𝑏𝑏1 𝑎𝑎2 ^𝑏𝑏2 𝑎𝑎3 ^𝑏𝑏3 𝑎𝑎4 ^𝑏𝑏4 ]

Element-by-element multiplication, division and exponentiation of two matrices gives:

𝑎𝑎11 𝑎𝑎12 𝑎𝑎13 𝑏𝑏11 𝑏𝑏12 𝑏𝑏13


𝑎𝑎
𝐴𝐴 = � 21 𝑎𝑎22 𝑎𝑎23 � 𝐵𝐵 = �𝑏𝑏21 𝑏𝑏22 𝑏𝑏23 �
𝑎𝑎31 𝑎𝑎32 𝑎𝑎33 𝑏𝑏31 𝑏𝑏32 𝑏𝑏33

𝑎𝑎11 𝑏𝑏11 𝑎𝑎12 𝑏𝑏12 𝑎𝑎13 𝑏𝑏13


𝐴𝐴.∗ 𝐵𝐵 = �𝑎𝑎21 𝑏𝑏21 𝑎𝑎22 𝑏𝑏22 𝑎𝑎23 𝑏𝑏23 �
𝑎𝑎31 𝑏𝑏31 𝑎𝑎32 𝑏𝑏32 𝑎𝑎33 𝑏𝑏33

𝑎𝑎11 /𝑏𝑏11 𝑎𝑎12 /𝑏𝑏12 𝑎𝑎13 /𝑏𝑏13


𝐴𝐴./𝐵𝐵 = �𝑎𝑎21 /𝑏𝑏21 𝑎𝑎22 /𝑏𝑏22 𝑎𝑎23 /𝑏𝑏23 �
𝑎𝑎31 /𝑏𝑏31 𝑎𝑎32 /𝑏𝑏32 𝑎𝑎33 /𝑏𝑏33

𝑎𝑎11 ^𝑏𝑏11 𝑎𝑎12 ^𝑏𝑏12 𝑎𝑎13 ^𝑏𝑏13


𝐴𝐴. ^𝐵𝐵 = � 21 ^𝑏𝑏21
𝑎𝑎 𝑎𝑎22 ^𝑏𝑏22 𝑎𝑎23 ^𝑏𝑏23 �
𝑎𝑎31 ^𝑏𝑏31 𝑎𝑎32 ^𝑏𝑏32 𝑎𝑎33 ^𝑏𝑏33

Examples:

A=
21 7 6
9 45 12
92 6 4
>> B
B=
73 92 15
41 54 6
8 37 9
>> A.*B
ans =
1533 644 90
369 2430 72
736 222 36
>> A./B
ans =
0.2877 0.0761 0.4000
0.2195 0.8333 2.0000
11.5000 0.1622 0.4444

22
>> A.^2
ans =
441 49 36
81 2025 144
8464 36 16

2.11 Inverse of a Matrix


Any non-singular square matrix A has its multiplicative inverse, denoted by A-1. In MATLAB
the inverse of a matrix can be calculated using the function inv(A) or can be obtained by raising
A to the power of -1. For example,

A=
21 7 6
9 45 12
92 6 4
>> inv(A)
ans =
-0.0073 -0.0005 0.0126
-0.0723 0.0317 0.0134
0.2766 -0.0351 -0.0597
>> A^-1
ans =
-0.0073 -0.0005 0.0126
-0.0723 0.0317 0.0134
0.2766 -0.0351 -0.0597

2.12 Determinant
A determinant is a function associated with square matrices. The determinant of a square matrix
can be calculated with the det command. Example,

A=
21 7 6
9 45 12
92 6 4
>> det(A)
ans =
-14772

Solving Linear System: Suppose A is a nonsingular nxn matrix and b is a column vector of
length n. Then typing x = A\b numerically computes the unique solution to A*X= b.

Example, consider the following system of equations:

5𝑥𝑥 + 2𝑦𝑦 9𝑧𝑧 = 44

23
9𝑥𝑥 2𝑦𝑦 + 2𝑧𝑧 = 11

6𝑥𝑥 + 7𝑦𝑦 + 3𝑧𝑧 = 44

The above system of equations in the form of a matrix can be written as,

5 2 9 𝑥𝑥 44
�9 2 2� �𝑦𝑦� = �11�
6 7 3 𝑧𝑧 44
So the solution o the given system of equations is,

>> X=A\b
X=
-5.1602
12.8124
-4.9085

2.13 Eigenvalues and Eigenvectors

To build a column vector containing the eigenvalues of the matrix B, use E = eig(B).

Example:

B=
3 8 12
14 24 32
15 7 19
>> y=eig(B)
y=
44.0545
-3.2288
5.1743

To build a matrix V whose columns are the eigenvectors of the matrix B and another matrix D
whose diagonal elements are the eigenvalues corresponding to the eigenvectors in V use [V, D]
= eig(B). Example,

>> [V,D]=eig(B)
V= % A matrix whose elements are the eigenvectors of B.
-0.2893 -0.7334 -0.1059
-0.8630 -0.3247 -0.8361
-0.4143 0.5972 0.5382
D= % A matrix whose diagonal elements are the eigenvalues of B.
44.0545 0 0
0 -3.2288 0
0 0 5.1743

24
3 SCRIPT

So far all the commands were typed in the Command Window and were executed when the Enter
key was pressed. The commands in the Command Window cannot be saved and executed again.
If a change or a correction is needed in a command that was previously executed and the results
of this command are used in commands that follow, all the commands have to be entered and
executed again.

A different (better) way of executing commands with MATLAB is first to create a file with a list
of commands (program), save it, and then run (execute) the file. When the file runs, the
commands it contains are executed in the order that they are listed. If needed, the commands in
the file can be corrected or changed and the file can be saved and run again. Files that are used
for this purpose are called script files.

Notes about Script File:

• A script file is a sequence of MATLAB commands, also called a program.


• When a script file runs, MATLAB executes the commands in the order they are written.
• When a script file has a command that generates an output, the output is displayed in the
Command Window.
• Using a script file is convenient because it can be edited and executed many times.
• Script files are also called M-files because the extension .m is used when they are saved.

3.1 Creating and Saving a Script File


In MATLAB script files are created and edited in the Editor/Debugger Window. This window is
opened from the Command Window. In the File menu, select New, and then select Script. An
open Editor/Debugger Window is shown in Figure 3.1. Once the window is open, the commands
of the script file are typed line by line. MATLAB automatically numbers a new line every time
the Enter key is pressed. The commands can also be typed in any text editor or word processor
program and then copied and pasted in the Editor/Debugger Window. An example of a short
program typed in the Editor/Debugger Window is shown in Figure 3.2. The first few lines in a
script file are comments that describe the program written in the script file.

25
Run icon

Figure 3.1. The Editor Window.

Before a script file can be executed it has to be saved. This is done by choosing Save As... from
the File menu, selecting a location, and entering a name for the file. When saved, MATLAB adds
the extension .m to the name.
Example:

% script example1.m
% This program calculate the square root of the numbers 1 through 10
x=[1:10]
y=sqrt(x)

Figure 3.2. Example of a script file.

26
3.2 Running (Executing) a Script File

A script file can be executed either directly from the Editor Window by clicking on the Run icon
(see Figure 3.1) or by typing the file name in the Command Window and then pressing the Enter
key. For a file to be executed, MATLAB needs to know where the file is saved. The file will be
executed if the folder where the file is saved is the current folder of MATLAB.

Current Folder
Browser

Figure 3.3. Saving a script file.


3.3 Current Folder
The current folder is shown in the Current Folder field in the desktop tool bar of the Command
Window, as shown in Figure 3.3. The user can then change the current folder to the folder where
the script file is saved, or add it to the search path. The Current Folder can be changed by
choosing the drive and folder where the file is saved. An alternative simple way of to change the
current folder is to use the cd (change directory) command in the Command Window. To change
the current folder to a different drive, type cd, space, and then the name of the directory followed
by a colon : and press the Enter key. For example, to change the current folder to drive F (e.g.,
the flash drive) type cd F:. If the script file is saved in a folder within a drive, the path to that
folder has to be specified. This is done by typing the path as a string in the cd command. For
example,

>> cd d: % Change the current folder to drive D.


>> example1 % Execute the file example1.m save in d drive.
x=
1 2 3 4 5 6 7 8 9 10
y=
Columns 1 through 9
1.0000 1.4142 1.7321 2.0000 2.2361 2.4495 2.6458 2.8284 3.0000
Column 10
3.1623

Then the script file from Figure 6, which was saved in drive D as example1.m, is executed by
typing the name of the file and pressing the Enter key.

27
3.4 The input command

The input command is used for creating a variable in the script file and when the file is
executed, the user is prompted to assign a value to the variable in the command window. The
format of the input command is:

Variable_name=input(‘string with the message that is displayed in the command


window’)

When the script file is executed the string will be displayed in the command window, prompting
the users to enter a value. Example to demonstrate the input command:

% script inpexample.m
% To find the average of three numbers.
val1=input('Enter the first value: ');
val2=input('Enter the second value: ');
val3=input('Enter the third value: ');
avg_val=(val1+val2+val3)/3

The above program is save as inpexample.m. In the Command Window the program is executed,

>> inpexample
Enter the first value: 42
Enter the second value: 22
Enter the third value: 56

avg_val =

40

In the above example scalars are assigned to the variable. However vectors or arrays can also be
assigned to the variable by typing the arrays in the same way that is used to assign a variable.
Example:

>> inpexample
Enter the first value: [34 78 62]
Enter the second value: [42 53 49]
Enter the third value: [73 62 88]

avg_val =

49.6667 64.3333 66.3333

3.5 The Output Commands

Two commands that are frequently used to generate output are the disp and fprintf.

28
The disp Command: The disp command is used to display the elements of a variable without
displaying the name of the variable, and to display text. Its format is:

disp(name of the variable) or disp('text as string').

Example:

% script dispexample.m
% to find the total marks scored by a student.
mark1=input('Enter the marks scored in Test 1: ');
mark2=input('Enter the marks scored in Test 2: ');
mark3=input('Enter the marks scored in assignment: ');
mark4=input('Enter the marks scored in Final: ');
total=mark1+mark2+mark3+mark4;
disp('The total marks scored by a student is: ') This display text
disp(total)
This display total value
The above program is save as dispexample.m. In the Command Window the program is
executed,

Enter the marks scored in Test 1: 16


Enter the marks scored in Test 2: 12
Enter the marks scored in assignment: 8
Enter the marks scored in Final: 33
The total marks scored by a student is:
69

Every time the disp command is executed, the display it generates appears in a new line.

The fprintf Command: The fprintf command can be used to display output (text and data)
on the screen. In this command, text and numerical values of variables can be intermixed and
displayed in the same line. The format for fprintf command to display text is:

fprintf('text typed as string')

Example:

fprintf('this is my MATLAB class\n') % part of script file.

When the line is executed the following is displayed in the command window.

this is my MATLAB class

When a program having more than one fprintf command is executed, the display that they
generate is a continuous line.

fprintf('College of Natural and Computational Sciences ')


fprintf('Department of Mathematics ')

29
When the line is executed the following is displayed in the command window.

College of Natural and Computational Sciences Department of Mathematics >>

To start a new line \n must be typed at the start of the string.


Example:

fprintf('College of Natural and Computational Sciences ')


fprintf('\nDepartment of Mathematics\n ')
To bring the command prompt in a new line

To display the string in a new line

When the line is executed the following is displayed in the command window.

College of Natural and Computational Sciences


Department of Mathematics
>>

The \n is called an escape character. Other escape character used in MATLAB are \b (backspace)
and \t (horizontal tab).

The fprintf command can be used to display a mixed of text and numerical data. The format
is,

fprintf(‘text as string %5.3f additional text’, variable name)

% indicates the Conversion character


Field Name of the variable
place where
width whose value is
number is Precision
displayed
inserted

Table 3.1. Common notations for conversion character.

Notation Description
e Exponential notation using lower case e (eg. 7.071068e-001)
E Exponential notation using upper case E (eg. 7.071068E-001)
f Fixed point notation (eg. 0.707107)
i or d Integer.
s or c Character

If an integer or string conversion is applied to a numeric value that contains a fraction,


MATLAB overrides the specific conversion and uses %e.

Example:

30
% script SqrtExample2.m
% to find the square root of the number 1, 2,....5.
x=1:5;
y=sqrt(x);
u=[x;y];
fprintf('the square root of %i is %2.3f \n',u)

When the file SqrtExample2.m is executed the following is displayed in the command window.

the square root of 1 is 1.000


the square root of 2 is 1.414
the square root of 3 is 1.732
the square root of 4 is 2.000
the square root of 5 is 2.236

3.6 Importing and Exporting Data


MATLAB is often used for analyzing experimental data. This is done by importing the data into
MATLAB and the analyze data is exported in a file. Importing data can be done either by using
commands, or by using the Import Wizard. Exporting data can be done by using commands. In
this section we will transfer data into and out of the Excel Spreadsheets.

Importing and exporting data into and from Excel using commands: Importing data from Excel is
done with the xlsread command. When the command is executed, the data from the
spreadsheet is assigned as an array to a variable. The simplest form of the xlsread command
is:

Variable_name=xlsread(‘filename’)

Example:

>> a=xlsread('Example1') % Example1is the name of the Excel file and the data is assigned to the
% array a.
a=

4 1 5
2 1 3
1 0 4
3 1 3
3 1 5
1 1 5
1 1 3

When an Excel file has several sheets, the xlsread command can be used to import data from
a specified sheet. The form of the command is:

Variable_name=xlsread(‘filename’, ‘sheet_name’)

31
Exporting data from MATLAB to an Excel spreadsheet is done by using the xlswrite
command. The simplest form of the command is:

xlswrite(‘filename’, variable_name)

Example:

>>xlswrite('Example2',a) % the data contained in array a is exported to the Excel file Example2.

Using Import Wizard: Importing data using the import wizard can be done by selecting Import
data in the File menu of the Command Window. Select the file which contains the data to be
imported from the file selection box. Click open to open the import wizard. The display of the
import wizard is shown in the Figure 3.4.

Figure 3.4. Import Wizard Window.

Click Next and click finish as shown in the Figure 3.5.

32
Figure 3.5. Import wizard for selecting variables.

In the Command Window of MATLAB, the imported data can be displayed by typing the name
of the variable.

>> data
data =
4 1 5
2 1 3
1 0 4
3 1 3
3 1 5
1 1 5
1 1 3

33
4 LOOPS AND CONDITIONAL STATEMENT

In most of the scripts we have seen so far the commands are executed consecutively, working
down the script from the top to the bottom. Those programs are the simple programs. However in
sophisticated programs we may want the command not to execute in the order it is typed, or that
different commands are executed when the program runs with different input variables.
Conditional statements and switch structure make it possible to skip commands or to execute
specific groups of commands in different situations. In other situation we may want to repeat a
sequence of commands several times within a program. Using For loops and while loops
make it possible to repeat a sequence of commands several times.

Changing the flow of a program requires decision-making process within the program. This
decision making is done by comparing values of a variable using relational and logical operators.

4.1 Relational and Logical Operators


A relational operator compares two numbers by determining whether a comparison statement
(eg, 6<19) is true or false. If the statement is true, it is assigned the value 1, if it is false it is
assigned the value 0. A logical operator examines true/false statements and produces a result
which is true (1) or false (0) according to the specific operator. For example, the logical AND
operator gives 1 only if both statements are true. Relational and logical operators can be used in
mathematical expressions and are frequently used in combination with other commands, to make
decisions that control the flow of a computer program.

Table 4.1. Relational operator in MATLAB.

Relational Operator Description


< Less than
> Greater than
<= Less than or equal to
>= Greater than or equal to
== Equal to
~= Not equal to

Example:

34
>> 7<2 % Compare whether 7 is less than 2 which is false and return the answer 0.
ans =
0
>> 2<9 % Checks whether 2 is less than 9 which is true and return the answer 1.
ans =
1
>> x=(5<22)+(48>33)-(42/2==7*3) % Use relational operator in mathematical expression.

Answer is 1 since 5 Answer is 1 since


Answer is 1 since 48 42/2 is equal to 7*3
is less than 22
is greater than 33
x=
1
>> a=[23 6 17 28 12]; b=[14 52 73 9 21];
>> y=a<=b % Compare two vector elements.
y=
0 1 1 0 1
>> u=a>=b
u=
1 0 0 1 0
>> v=a~=b % Checks which a elements are not equal to c elements.
v=
1 1 1 1 1

Table 5.2. Logical operators in MATLAB.

Logical operator Name Description


& AND Operates on two relational expressions. If both are true, the result is true (1),
otherwise the result is false (0).
| OR Operates on two relational expressions. If either one or both are true, the
result is true (1), otherwise the result is false (0).
~ NOT Operates on one relational expression. True (1) if the operand is false, and
false (0) if the operand is true.

Arithmetic, relational and logical operators can all be combined in mathematical expressions.
When an expression has such a combination, the result depends on the order in which the
operations are carried out.
Table 4.3. Order of precedence.

Precedence Operation
1 (highest) Parantheses
2 Exponentiation
3 Logical NOT (~)
4 Multiplication, Division
5 Addition, Subtraction
6 Relational Operators
7 Logical AND (&)
8 Logical OR (|)

35
>> z=-6; t=20;
>> -10<z<-4 % In this inequality the operation is executed from left to right starting from
%-10<z which is true (1) and then 1<-1 which is false and the answer is 0, which is wrong.
ans =
0
>> -10<z & z<-4 % This is the correct mathematical statement. First the inequalities are
% executed then the logical operation is executed.
ans =
1
>> ~(t>=34)
ans =
1
>> ~t>34
ans =
0
>> (t<=30)|(z>=1)
ans =
1

4.2 Loops
In a loop, the execution of a command, or a group of commands, is repeated several times
consecutively. Each round of execution is called a pass. In each pass at least one variable, but
usually more than one, or even all the variables that are defined within the loop are assigned new
values. MATLAB has two kinds of loop. They are:
1. for-end loops: The number of passes is specified when the loop starts.
2. while-end loops: The number of passes is not known ahead of time, and the looping
process continuous until a specified condition is satisfied.

4.2.1 for-end Loop

In for-end loops the execution of a command, or a group of commands, is repeated a


predetermined number of times. It often appears in script files. The format of the loop is,

for x= array
(commands)
end

Commands in the for and end statements are executed repeatedly for each elements in the array
(vector). In the first statement x = array, x is a loop index variable which is assigned an
array (vector). At each iteration, x is assigned to the next element of a vector. Any numerical
array can be used. Below examples demonstrate the for-end loop.

% script exfor_loop1.m
% To print a text 5 times
for i=1:5 % The loop index variable i is assigned a row vector with
% elements i=1, 2, 3, 4, 5 and commands between for-end loop
% will be executed 5 times i.e., for each element in the loop.

36
disp('My MATLAB Class')
end

When the file exfor_loop1.m is executed the text 'My MATLAB Class” is displayed 5 times in the
command window.

My MATLAB Class
My MATLAB Class
My MATLAB Class
My MATLAB Class
My MATLAB Class

% script exfor_loop2.m
for k=1:3:10 % k=1, 4, 6, 10 the command between for end loop will be
% executed 4 times.
x=k^2
end

When the file exfor_loop2.m is executed the following is displayed in the command window.

x=
1
x=
16
x=
49
x=
100

% script exmult7.m
%To display the multiple of 7 from 1 to 10
for i=1:10
x=7*i;
fprintf(' 7 times %d is = %d\n',i,x);
end

When the file exmult7.m is executed the following is displayed in the command window.

7 times 1 is = 7
7 times 2 is = 14
7 times 3 is = 21
7 times 4 is = 28
7 times 5 is = 35
7 times 6 is = 42
7 times 7 is = 49
7 times 8 is = 56
7 times 9 is = 63
7 times 10 is = 70

% script exsum1.m
% To find the sum of the series ∑𝑛𝑛𝑖𝑖=1 2𝑛𝑛

37
sum=0;
n= input(' Enter the value of n: ');
for i=1:n
sum=sum+2^n;
end
fprintf('sum of the series upto %i terms is %i\n',n,sum)

When the file exsum1.m is executed the following is displayed in the command window.

Enter the value of n: 5


sum of the series upto 5 terms is 160

4.2.2 while-end Loop

while-end loops are used in situations when looping is needed but the number of passes is not
known ahead of time. In while-end loops the number of passes is not specified when the
looping process starts. Instead, the looping process continuous until a stated condition is
satisfied. The format of a while-end loop is,

while conitional expression


(commands)
end

The first line is a while statement that includes a conditional expression. When the program
reaches this line the conditional expression is checked. If it is false (0), MATLAB skips to the
end statement and continuous with the program. If the conditional expression is true (1),
MATLAB executes the group of commands that follow between the while and end command.
Then MATLAB jumps back to the while command and checks the conditional expression. This
looping process continuous until the conditional expression is false. Below examples
demonstrate the while-end loop.

% script exwhileloop1.m
x=5;
while x<=15 % The conditional expression is x<=15, if it is true the
% commands will be executed otherwise it will go out of the loop.
x=x+3;
disp('Center for Natural and Computational Sciences')
end

When the file exwhileloop1.m is executed the following is displayed in the command window.

Center for Natural and Computational Sciences


Center for Natural and Computational Sciences
Center for Natural and Computational Sciences
Center for Natural and Computational Sciences

% script exwhileloop2.m
sum=0;
x=1;
while (1+x)>1

38
x=x/2;
sum=sum+1;
end
disp('The sum is ')
disp(num)

When the file exwhileloop2.m is executed the following is displayed in the command window.

The sum is
53

4.3 Conditional Statements


The conditional statement is a command that allows MATLAB to make a decision of whether to
execute a group of commands that follow the conditional statement, or to skip these commands.
In a conditional statement a conditional expression is stated. If the expression is true a group of
commands that follow the statement is executed. If the expression is false, the computer skips the
group of commands. Conditional statement can be part of a program written in a script file or a
function file. The basic form of a conditional statement is:

If conditional expression
(Commands)
end

The commands between the if-end statements are evaluated if all elements in the expression
are true (nonzero). Example to demonstrate if-end statement is given below.

% script exif_end1.m
A=[12 34 6; 71 -8 11; 63 14 92];
[n,m]=size(A);
if n==m
disp('A is a square matrix')
end

When the file exif_end1.m is executed the following is displayed in the command window.

A is a square matrix

The if statement is commonly used in three structures: if-end, if-else-end, and if-
elseif-else-end.

4.3.1 if-else-end Structure

The format of if-else-end structure is,

if conditional expression
(commands 1)
else
(commands 2)

39
end

Here if the conditional expression in the first line is true, the program executes commands 1
between the if and the else statements and then skip to the end. If the conditional expression is
false, the program skips to the else, and then executes the command 2 between the else and end
statement. Example to demonstrate if-else-end statement is given below.

% script exif_end2.m
n=input('Enter a number: ');
if n>=1
x=log(n);
fprintf('The value of log%f is %f.\n',n,x)
else
fprintf('log%f is not define \n',n)
end

When the file exif_end2.m is executed the following message is displayed in the command
window asking user to input a number.

Enter a number:

The number 6.7 is entered. As soon as the number is entered MATLAB check the conditional
expression and gives the output.

Enter a number: 6.7


The value of log6.700000 is 1.902108.

If -1 is entered as input, the output is,

Enter a number: -1
log-1.000000 is not define

4.3.2 if-elseif-else-end Structure

The format of if-elseif-else-end structure is,

if conditional expression
(commands 1)
elseif
(commands 2)
else
(commands 3)
end

Here if the conditional expression in the first line is true, the program executes commands 1
between the if and the elseif statements and then skip to the end. If the conditional expression is
false, the program skips to the elseif statement. If the conditional expression in the elseif
statement is true the program executes the commands 2 and then skips to the end. If the condition

40
expression in elseif statement if false the program skips to the else and execute commands 3.
Example to demonstrate if-elseif-else-end statement is given below.

% script exif_end3.m
% To construct a conditional statement which evaluates the function:𝑓𝑓(𝑥𝑥) =
0 𝑥𝑥 < 0
𝑥𝑥 0 < 𝑥𝑥 ≤ 1
� � �
2 − 𝑥𝑥 1 < 𝑥𝑥 ≤ 2
0 𝑥𝑥 > 2

x=input('Enter a number : ');


if x>=0 & x<=1
f=x;
elseif x>1 & x<=2
f=2-x;
else
f=0;
end
fprintf(' The function value for x=%f is %f \n',x,f)

When the file exif_end3.m is executed the following message is displayed in the command
window asking user to input a number.

Enter a number:

The number 1.987 is entered. As soon as the number is entered MATLAB check the conditional
expression and gives the output.

Enter a number : 1.987


The function value for x=1.987000 is 0.013000

If 0.1118 is entered as input, the output is,

Enter a number : 0.1118


The function value for x=0.111800 is 0.111800

If 5 is entered as input, the output is,

Enter a number : 5
The function value for x=5.000000 is 0.000000

If we would like to add more conditions, several elseif statements and associated group of
commands can be added in the if-end conditional statement. The else statement is optional.
This means that in the case of several elseif statements and no else statement, if any of the
conditional statements is true the associated commands are executed, but otherwise nothing is
executed. Example:

% script exif_end4.m
m=input('Enter the marks scored by a student out of 100: ');
if m>85

41
disp('Grade=A')
elseif m>75 & m<=85
disp('Grade=B')
elseif m>65 & m<=75
disp('Grade=C')
elseif m>50 & m<=65
disp('Grade=D')
elseif m<=50
disp('Grade=Fail')
end

When the file exif_end4.m is executed the following message is displayed in the command
window asking user to input a number.

Enter the marks scored by a student out of 100:

The number 89 is entered and the output is,

Enter the marks scored by a student out of 100: 89


Grade=A

4.4 The switch-case Structure

The switch structure is similar in spirit to the if ….. elseif structure. However rather than testing
individual conditions, the branching is based on the value of a single test expression. Depending
on its value, different blocks of code are implemented. In addition, an optional block is
implemented if the expression takes on none of the prescribed values. The format is,

switch test expression


case value1
commands1
case value2
commands2
case value3
commands3
otherwise
commands4
end

The first line is the switch command which contain a test expression. The test expression can be
number, string or a computable expression. Following the switch statement there are several case
commands each having a value, associated with a group of commands. The value of the switch
expression in the switch command is compared with the case values. If a match is found the
commands following the case statement with the match are executed and skip to the end. If a
match is not found the program will execute the statement otherwise and the command between
otherwise and end statements. Example to demonstrate switch-case statement is given below.

% script exswitch_case1.m
grade=input('Enter a grade: ');
switch grade
case 'A'

42
disp('Excellent')
case 'B'
disp('Good')
case 'C'
disp('Mediocre')
case 'D'
disp('Woops')
otherwise
disp(' Fails ')
end

When the file exswitch_case1.m is executed the following message is displayed in the command
window asking user to input a character.

Enter a grade:

The character ‘D’ is entered and the output is,

Enter a grade: 'D'


Woops

4.5 Nested Loops and Conditional Statements


Loops and condition statements can be nested within themselves and each other. This means that
a loop and/or a conditional statement can start (and end) within another loop and/or condition
statement. There is no limit to the number of loops and conditional statements that can be nested.
It must be noted that each for, while, if and case must have a corresponding end
statement. The structure of a nested for-end loop is shown below.

for k=1:n
for i=1:m
(commands)
end
end

In the loops shown above if n=2 and m=4, then first k=1 and the nested loop execute four times
with i=1, 2, 3 and 4. Next k=2 and the nested loop execute four times with i=1, 2, 3 and 4. An
example to demonstrate this is given below.

% script exmatrix.m
% to form a 3x3 matrix whose elements aij=i+j, using nested for loop.
for i=1:3
for j=1:3
a(i,j)=i+j;
end
end
disp(a)

When the file exmatrix.m is executed the following is displayed in the command window.

2 3 4

43
3 4 5
4 5 6

4.6 The break and continue Commands

The break and continue statement alter the normal flow of a program. Loops perform a set
of repetitive task until text expression becomes false but it is sometimes desirable to skip some
statement/s inside loop or terminate the loop immediately without checking the test expression.
In such cases, break and continue statements are used.

4.61 The break Command:

The break command is used in terminating the for or while loop immediately after it is
encountered. When the break command appears in a loop, MATLAB jumps to the end
command of the loop and continues with the next command. In nested loops, break exits only
from the loop in which it occurs. The break statement is used with conditional if statement.
Example to demonstrate the break command is given below:

% script exbreak1.m
% Program to demonstrate the working of break command.
n=input('Enter maximum number of inputs: ');
sum=0;
j=0;
for i=1:n
u=input('Enter a number: ');
if u<0.0
break
end
j=j+1;
sum=sum+u;
end
avg=sum/j;
fprintf('Average value of %i numbers is %f \n',j,avg)

When the file exbreak1.m is executed the following message is displayed in the command
window.

Enter maximum number of inputs: 4 4 is entered


Enter a number: 32
Enter a number: 72
-11< 0 loops terminated in third iteration and
Enter a number: -11
execute the statement after the end statement
Average value of 2 numbers is 52.000000

4.62 The continue Commands:

It is sometimes desirable to skip some commands inside the (for or while) loop. In such
cases, continue commands are used. When the continue command appears in the loop it stop

44
the present pass and start the next pass in the looping process. The continue statement is used
with conditional if statement. Example to demonstrate the continue command is given below:

% script excontinue1.m
prod=1;
n=input('Enter maximum number of inputs: ');
j=0;
for i=1:n
x=input('Enter a number: ');
if x==0
continue
end
j=j+1;
prod=prod*x;
end
fprintf('The product of %i non-zero numbers is %f \n',j,prod)

When the file excontinue1.m is executed the following message is displayed in the command
window.

Enter maximum number of inputs: 5 5 is entered


Enter a number: 45
Enter a number: 12
Enter a number: 0 X=0, stop the third iteration and
Enter a number: 0 starts the next iteration
Enter a number: 13
The product of 3 non-zero numbers is 7020.000000

45
5 FUNCTIONS AND PLOTS

We have seen built-in functions in MATLAB such as abs, sqrt, …. etc. These functions
accept the input value passed by the user and passes the output back to the user. We cannot see
the commands and the variables created inside these functions. MATLAB provides a structure
for creating function of our own in the form of text M-files.

Plots are very useful tool for presenting information. MATLAB offers a variety of data plotting
functions plus a set of tools to create and modify graphic displays. In this chapter we will
describe how to create and format two-dimensional and three-dimensional plots.

5.1 Functions
A function file is created in the editor/Debugger window like the script file. It has the file
extension .m. Function files start with the word function. In contrast to the script files, they can
accept input arguments and return outputs.
Syntax for the function file is:

function [outvar]=func_name(arglist)
outvar=value;

Explaination:
1. First line tells that this is a function, and the name of the function is func_name.
outvar=name of the output variable, and is enclosed within square brackets [].
arglist=the functions input argument list, and is enclosed within round brackets ().
2. Second line performs the calculations.

The function is always saved by the name func_name .m. An input argument can be a number, a
computable expression, or it can be a variable that has assigned value. Example to demonstrate a
function file that takes one input and one output is given below.

function [output]=xsq(input)
output=input.^3;

46
The above function is saved in the name xsq.m. The function can be called from a command
window, from a script file or from another function file. The function can be used by assigning
its output to a variable (or variables), as a part of mathematical expression, as an argument in
another function, or just by typing its name in the Command Window or script file with the input
argument. Now we access the function from the Command Window.

>> xsq(9) % input argument is a scalar.


ans =
729
>> u=[21 17 15];
>> xsq(u) % input argument is a vector.
ans =
9261 4913 3375

We can create functions that take multiple inputs and give multiple outputs. We will demonstrate
this by using examples.

function [sq, cub]=xpower(input)


sq=input.^2;
cub=input.^3;

The above function xpower, take one input and give two outputs. The function is call from the
command window as,

>> [u1,u2]=xpower(23) % input argument is a vector.


u1 =
529
u2 =
12167
>> a=1:2:10;
>> [u1,u2]=xpower(a) % input argument is a vector.
u1 =
1 9 25 49 81
u2 =
1 27 125 343 729

function [out1, out2]=multi(in1, in2, in3)


out1=in1+max(in2,in3);
out2=(in1+in2+in3)/3;

The above function multi, take three inputs and give two outputs. The function is call from the
command window as,

>> [y1, y2]=multi(32, 77,53)


y1 =
109
y2 =
54

47
5.2 inline Functions

The inline command allows us to create a function of any number of variables by giving a string
containing the function followed by a series of strings denoting the order of the input variables.
This method is good for relatively simple functions that will not be used often and that can be
written in a single expression. Inline function can be defined in any part MATLAB. The format
of the inline command is,

name = inline(‘math expression typed as string’)

Expression can contain any number of independent variable. The expression must be written
according to the dimension of the argument (element-by-element or linear algebra calculations).
The expression cannot contain preassigned value. Examples to demonstrate inline function
with one independent variable are:
2
% The function 𝑓𝑓(𝑥𝑥) = 𝑒𝑒 𝑥𝑥 ⁄√𝑥𝑥 2 + 5 is defined as an inline function.

>> FX=inline('exp(x^2)/sqrt(x^2+5)') % An inline function FX is define for x as a scalar.


FX =
Inline function:
FX(x) = exp(x^2)/sqrt(x^2+5)
>> FX(21) % The function is used by assigning a value 21.
ans =
1.5820e+190
>> FX=inline('exp(x.^2)./sqrt(x.^2+5)') % An inline function FX is define for x as a vector.
FX =
Inline function:
FX(x) = exp(x.^2)./sqrt(x.^2+5)
>>FX([1 0.3 0.9]) % The function is used by assigning a vector.
ans =
1.1097 0.4850 0.9326

Inline function with several independent variable can be written using the format:

name = inline(‘math expression typed as string’, ‘arg1’, ‘arg2’, ‘arg3’)

Example to demonstrate inline function with multiple independent variables is:

% The function 𝑓𝑓(𝑥𝑥) = 2𝑥𝑥 2 − 4𝑥𝑥𝑥𝑥 + 𝑦𝑦 2 is defined as an inline function.

>> c=inline('2*x^2-4*x*y+y^2', 'x', 'y') % An inline function c is define for x as a scalar.


c=
Inline function:
c(x,y) = 2*x^2-4*x*y+y^2
>> c(3,6)
ans =
-18
>> c=inline('2*x.^2-4*(x.*y)+y.^2', 'x', 'y') % An inline function c is define for x as a vector.

48
c=
Inline function:
c(x,y) = 2*x.^2-4*(x.*y)+y.^2
>> c([2 1.3 4.6],[-3 6 7.9])
ans =
41.0000 8.1800 -40.6300

5.3 Two-Dimensional Plots


The plot command is used to create two dimensional plots. The simplest form of the command
is,

plot(x,y)

The arguments x and y are vector (one-dimensional array), both having the same number of
elements. When the plot command is executed a figure is created in the Figure Window. The
Figure window opens automatically when the command is executed. To plot the quadratic
𝑥𝑥 2 + 7𝑥𝑥 − 3 from −3 ≤ 𝑥𝑥 ≤ 3 in steps of 0.2 , the command is written as:

>> x=-3:0.2:3;
>> y=x.^2+7*x-3;
>> plot(x,y)

Once the enter key is press at the end of the plot command a figure window opens and the plot is
displayed as shown in Figure 5.1.

Figure 5.1. Plot of 𝑥𝑥 2 + 7𝑥𝑥 − 3.

Plot command has additional optional arguments that can be used to specify the color and style
of the line and the color and type of markers, if any are desired. With these options the command
has the form:

Plot(x,y, ‘line specifiers’, ‘PropertyName’, PropertyValue)

49
Line specifiers: Line specifiers are optional and can be used to define the style and color of the
line and the type of the markers. There are three types of line specifiers. They are line style
specifiers, line color specifiers and line marker specifiers.

Table 5.1. The line style specifiers.

Line Style Specifier


solid (default) -
Dashed --
Dotted :
dash-dot -.

Table 5.2. The line color specifiers.

Line Color Specifier Line Color Specifier


Red r magenta m
Green g yellow y
Blue b black k
Cyan c white w

Table 5.3. The marker type specifiers.

Marker Type Specifier Marker Type Specifier


plus sign + square s
Circle o diamond d
Asterisk * five-point star p
Point . six-pointed star h

Examples to demonstrate using the line specifiers are given below:

Example 1.
>> X=[0:0.1:10];
>> Y=cox(X);
>> plot(x,y,'m.') Line Specifiers: magenta point marker

The plot displayed by the above command is shown in Figure 5.2.

50
Figure 5.2. Plot of cox(X).

>> plot(X,Y,'r:d')
Line Specifiers: dotted red line with
diamond marker

The plot displayed by the above command is shown in Figure .

Figure 5.3. Plot of cox(X) with Line Specifiers: dotted red line with diamond marker.

Property Name and Property Value: Properties are optional and can be used to specify the
thickness of the line, the size of the marker, and the colors of the marker’s edge line and fill. The
property Name is typed as a string, followed by a comma and a value for the property, all inside
the plot command.
Table 5.4. Properties names and values are:

Property Name Description Possible Property Values


LineWidth (or linewidth) Specifies the width of the line. A number in units of points (default
0.5).
MarkerSize(or markersize) Specifies the size of the marker. A number in units of points.
MarkerEdgeColor (or Specifies the edge color of the Same as line color specifiers.
markeredgecolor) marker.

51
MarkerFaceColor (or Specifies the face color of the Same as line color specifiers.
markerfacecolor) marker

Example 2:

>> x=-3:0.5:3;
>> y=x.^2+7*x-3;
>> plot(x,y,'m-o', 'linewidth', 2.5, 'markersize', 11, 'markeredgecolor','r', 'markerfacecolor','b')

The plot displayed by the above command is shown in Figure 5.5.

Figure 5.5. Plot of Example 2.

We can add grid to the plot. This is done by adding the phrase grid on to our plot statement.
For the next example, we will plot y = tanh(x) over the range −6 ≤ x ≤6 with a grid display.

>> x=-6:0.01:6;
>> y=tanh(x);
>> plot(x,y), grid on

The plot is shown in Figure 5.6.

Figure 5.6. Plot of Example 2 with grid on.

52
5.4 Plotting Multiple Graphs
Multiple graphs can be drawn in the same plot. There are three methods to draw the graphs. They
are the plot command, hold on and hold off commands and the third is line command.

plot command: The plot command:

plot(x,y,u,v,s,t)

creates three graphs: x vs y, u vs v and s vs t all in the same plot in different colors. Using the
line specifiers we can specify our own color. The vectors of each pair must be of the same
length.

Example 3: To plot the function 𝑦𝑦 = 3𝑥𝑥 2 − 26𝑥𝑥 + 10, and its first and second derivatives, for
−2 ≤ 𝑥𝑥 ≤ 4, all in the same plot.

>> x=-2:0.01:4;
>> y=3*x.^3-26*x+10;
>> y1d=9*x.^2-26;
>> y2d=18*x;
>> plot(x,y,'-r',x,y1d,'--b',x,y2d,':m')

The plot displayed by the above command is shown in Figure 5.7.

Figure 5.7. Plot of Example 3.

hold on, hold off commands: To plot several graphs using the hold on, hold off
commands , one graph is plotted first with the plot command. Then the hold on command is
type to keep the figure open and several plot commands are typed next. The hold off
command is typed at the last to stop this process. The above example is plotted using the hold
on, hold off commands in the script file.

x=-2:0.01:4;

53
y=3*x.^3-26*x+10;
y1d=9*x.^2-26;
y2d=18*x;
plot(x,y,'-r')
hold on
plot(x,y1d,'--b')
plot(x,y2d,':m')
hold off

line command: With the line command additional graphs can be added to a plot that already
exists. The format of the line command is almost the same as the plot command. The form of
the line command is:

line(x,y, ‘PropertyName’, PropertyValue )

Example 4: The above example is plotted using the line command in the script file.

x=-2:0.01:4;
y=3*x.^3-26*x+10;
y1d=9*x.^2-26;
y2d=18*x;
plot(x,y,'-r')
line(x,y1d, 'linestyle','--', 'color','c')
line(x,y2d, 'linestyle',':', 'color','m')

5.5 Formatting a Plot

Plots can be formatted by using MATLAB commands that follow the plot commands. The
various formatting commands are:

The xlabel and ylabel commands: Labels can be placed next to the axes with the xlabel
and ylabel commands which have the form:

xlabel(‘text as string’)
ylabel(‘text as string’)

Example 5: To plot y = tanh(x) over the range −6 ≤ x ≤6.

>> x=-6:0.01:6;
>> y=tanh(x);
>> plot(x,y)
>> xlabel('x')
>> ylabel('tanh(x)')

The plot displayed by the above command is shown in Figure 5.8.

54
Figure 5.8. Plot of Example 5.

The title command: A title can be added in the plot using the command,

title(‘text as string’)

Let’s return to the above example, which we now plot by adding the command,

>> title('plot of x versus tanh(x)')

The plot displayed is shown in Figure 5.9.

Figure 5.9. Plot of Example 5 with title.

The legend command: The legend command places a legend on the plot. The legend shows
a sample of the line type of each graph that is plotted. The form of the command is:

legend(‘string1’, ‘string2’)

The strings are the labels that are placed next to the line sample. Their order corresponds to the
order that the graphs were created.

55
Example 6: To plot two potential energy functions that is defined in terms of the hyperbolic
trignometric functions sinh(x) and cosh(x) for 0 ≤ x ≤2.

>> x=0:0.1:2;
>> y=sinh(x);
>> z=cosh(x);
>> plot(x,y, 'r--', x,z,'b-.')
>> xlabel('x')
>> ylabel('potential')
>> legend('sinh(x)', 'cosh(x)')

The plot displayed is shown in Figure 5.10.

Figure 5.10. Plot of Example 6.

The axis command: The axis command allows MATLAB to change the range and the
appearance of the axes. The form of the axis command is:

axis([xmin, Xmax, ymin, ymax])

Sets the limits of both the x and y axes (xmin, xmax, ymin and ymax are numbers)

axis equal  Sets the same scale for both axes.


axis square  Sets the axis region to be square.

Example 7: To plot 𝑦𝑦 = 𝑡𝑡𝑡𝑡𝑡𝑡ℎ(𝑥𝑥) over the range −6 ≤ 𝑥𝑥 ≤ 6.

>> x=-6:0.01:6;
>> y=tanh(x);
>> plot(x,y)
>> axis equal

The plot displayed is shown in Figure 5.11.

56
Figure 5.11. Plot of Example 7.

5.6 Three-Dimensional Plots

mesh and surface plots are three dimensional plots that can be used for plotting functions of
the form 𝑧𝑧 = 𝑓𝑓(𝑥𝑥, 𝑦𝑦) where the x and y are independent variables and z is dependent variable.
The mesh and surface plots are created in three steps. The first step is to create a grid in the x-
y plane that covers the domain of the function. The second step is to calculate the value of z at
each point of the grid. The third step is to create the plot. A mesh or surface commands, which
have the forms:

mesh(X, Y, Z) surf(X, Y,Z)

where X, Y, are matrices with the coordinates of the grid and Z is a matrix with the value of z at
the grid points. The mesh plot is made of lines that connect the points. In the surface plot,
areas within the mesh lines are colored. Examples to demonstrate mesh and surface plots are:

𝑥𝑥𝑦𝑦 2
Example 8. To plot 𝑧𝑧 = over the domain −1 ≤ 𝑥𝑥 ≤ 3 and 1 ≤ 𝑦𝑦 ≤ 4 using the mesh
𝑥𝑥 2 +𝑦𝑦 2
command.

x=-1:0.1:3;
y=1:0.1:4; x and y are the vectors that
divides the domain of x and y.
[X,Y]=meshgrid(x,y); % meshgrid is built-in function for creating the X
% and Y matrix.
X and Y are the matrices of
the x and y coordinates of the
grid points.

Z=X.*Y.^2./(X.^2+Y.^2); % Value of Z at each point of the grid.


mesh(X,Y,Z)
xlabel('x');
ylabel('y');
zlabel('z')

57
This plot is shown in Figure 5.12.

Figure 5.12. Plot of Example 8.

2 +𝑦𝑦 2
Example 9. To plot 𝑧𝑧 = −1.8−1.5�𝑥𝑥 sin 𝑥𝑥 𝑐𝑐𝑐𝑐𝑐𝑐0.5𝑦𝑦 over the domain −3 ≤ 𝑥𝑥 ≤ 3 and
−3 ≤ 𝑦𝑦 ≤ 3 using the mesh command.

x=-3:0.25:3;
y=-3:0.25:3;
[X,Y]=meshgrid(x,y);
Z=1.8.^(-1.5*sqrt(X.^2+Y.^2)).*sin(X).*cos(0.5*Y);
mesh(X,Y,Z)
xlabel('x');ylabel('y');zlabel('z')

This plot is shown in Figure 5.13.

Figure 5.13. Plot of Example 9.

To draw a contour plot beneath the mesh, we call the command meshc. We plot mesh and
contour, for the function given in Example 9 by simply changing the command mesh(X,Y,Z)
to meshc(X,Y,Z).

58
This plot is shown in Figure 5.14.

Figure 5.15. Mesh and Contour Plot of Example 9.

Now let’s plot the function given in Example 9, using a shaded surface plot. This is done by
calling the command surf. Simply changing the command mesh(X,Y,Z)to surf(X,Y,Z)

Gives us the plot as shown in Figure 5.16.

Figure 5.16. Surface Plot of Example 9.

To draw a contour plot beneath the surface, we call the command surfc. We plot surface and
contour, for the function given in Example 9 by simply changing the command mesh(X,Y,Z)
to surfc(X,Y,Z).

This plot is shown in Figure 5.17.

59
Figure 5.17. Surface and Contour Plot of Example 9.

60

You might also like