Matlab Training Manual-1-63
Matlab Training Manual-1-63
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
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
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
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 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:
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.
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.
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.
>>
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
≫ 4 + 6;
≫
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.
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.
4
Basic arithmetic operations offers by MATLAB are:
Table 1.4. Arithmetic Operators.
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.
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 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:
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
>> pi
ans =
3.1416
We notice that MATLAB displayed four decimal places. If we desire additional precision, type
the following:
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.
7
x=
6.666666666666666e-001
rat or rational Display rational number. >> format rat
>> x=8/7
x=
8/7
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:
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.
Row vector: To create a row vector type the elements with a space or a comma between the
elements inside the square brackets.
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:
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
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.
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.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.
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.
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
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).
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
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.
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
>>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,
Example:
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
Symbol Description
.* Multiplication
.^ Exponentiation
./ Right Division
.\ Left Division
21
Element-by-element multiplication, division and exponentiation of two vectors gives:
𝑎𝑎. ^𝑏𝑏 = [𝑎𝑎1 ^𝑏𝑏1 𝑎𝑎2 ^𝑏𝑏2 𝑎𝑎3 ^𝑏𝑏3 𝑎𝑎4 ^𝑏𝑏4 ]
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
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.
23
9𝑥𝑥 2𝑦𝑦 + 2𝑧𝑧 = 11
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
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.
25
Run icon
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)
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
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:
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 =
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:
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,
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:
Example:
When the line is executed the following is displayed in the command window.
When a program having more than one fprintf command is executed, the display that they
generate is a continuous line.
29
When the line is executed the following is displayed in the command window.
When the line is executed the following is displayed in the command window.
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,
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
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.
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.
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.
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.
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.
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.
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,
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.
% 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
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.
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: -1
log-1.000000 is not define
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
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 : 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.
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,
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:
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
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.
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.
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.
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.
We can create functions that take multiple inputs and give multiple outputs. We will demonstrate
this by using examples.
The above function xpower, take one input and give two outputs. The function is call from the
command window as,
The above function multi, take three inputs and give two outputs. The function is call from the
command window as,
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,
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.
Inline function with several independent variable can be written using the format:
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
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.
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:
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.
Example 1.
>> X=[0:0.1:10];
>> Y=cox(X);
>> plot(x,y,'m.') Line Specifiers: magenta point marker
50
Figure 5.2. Plot of cox(X).
>> plot(X,Y,'r:d')
Line Specifiers: dotted red line with
diamond marker
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:
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')
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
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(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')
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:
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')
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’)
>> x=-6:0.01:6;
>> y=tanh(x);
>> plot(x,y)
>> xlabel('x')
>> ylabel('tanh(x)')
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,
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 axis command: The axis command allows MATLAB to change the range and the
appearance of the axes. The form of the axis command is:
Sets the limits of both the x and y axes (xmin, xmax, ymin and ymax are numbers)
>> x=-6:0.01:6;
>> y=tanh(x);
>> plot(x,y)
>> axis equal
56
Figure 5.11. Plot of Example 7.
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:
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.
57
This plot is shown in Figure 5.12.
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')
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.
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)
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).
59
Figure 5.17. Surface and Contour Plot of Example 9.
60