See discussions, stats, and author profiles for this publication at: https://www.researchgate.
net/publication/365995382
MATLAB Lectures
Technical Report · December 2022
DOI: 10.13140/RG.2.2.25798.55366
CITATIONS READS
0 227
1 author:
 Faez Fawwaz
 University of Technology- iraq
 13 PUBLICATIONS 22 CITATIONS
 SEE PROFILE
 All content following this page was uploaded by Faez Fawwaz on 04 December 2022.
 The user has requested enhancement of the downloaded file.
Experiment No. (1) Introduction to MATLAB
 Experiment No. ( 1 )
 Introduction to MATLAB
1-1 Introduction
 MATLAB is a high-performance language for technical computing. It integrates
computation, visualization, and programming in an easy-to-use environment where problems
and solutions are expressed in familiar mathematical notation.
 The name MATLAB stands for matrix laboratory. MATLAB was originally written to
provide easy access to matrix.
1-1-1 Starting and Quitting MATLAB
 • To start MATLAB, double-click the MATLAB shortcut icon on your Windows
 desktop. You will know MALTAB is running when you see the special
 " >> " prompt in the MATLAB Command Window.
 • To end your MATLAB session, select Exit MATLAB from the File menu in the
 desktop, or type quit (or exit) in the Command Window, or with easy way by
 click on close button in control box.
1-1-2 Desktop Tools
 1- Command Window: Use the Command Window to enter variables and run
 functions and M-files.
 2- Command History: Statements you enter in the Command Window are logged in
 the Command History. In the Command History, you can view previously run
 statements, and copy and execute selected statements.
 3- Current Directory Browser: MATLAB file operations use the current directory
 reference point. Any file you want to run must be in the current directory or on the
 search path.
 4- Workspace: The MATLAB workspace consists of the set of variables (named
 arrays) built up during a MATLAB session and stored in memory.
 1
Experiment No. (1) Introduction to MATLAB
 Current Directory Browser Command Window
 Workspace
 Command
 History
 5- Editor/Debugger Window: Use the Editor/Debugger to create and debug M-files.
 2
Experiment No. (1) Introduction to MATLAB
1-2 Basic Commands
 • clear Command: Removes all variables from workspace.
 • clc Command: Clears the Command window and homes the cursor.
 • help Command: help <Topic> displays help about that Topic if it exist.
 • lookfor Command: Provides help by searching through all the first lines of
 MATLAB help topics and returning those that contains a key word you specify.
 • edit Command: enable you to edit (open) any M-file in Editor Window. This
 command doesn’t open built-in function like, sqrt. See also type Command.
 • more command: more on enables paging of the output in the MATLAB
 command window, and more off disables paging of the output in the MATLAB
 command window.
Notes:
 • A semicolon " ; " at the end of a MATLAB statement suppresses printing of results.
 • If a statement does not fit on one line, use " . . . ", followed by Enter to indicate that
 the statement continues on the next line. For example:
 >> S= sqrt (225)*30 /...
 (20*sqrt (100)
 • If we don’t specify an output variable, MATLAB uses the variable ans (short for
 answer), to store the last results of a calculation.
 • Use Up arrow and Down arrow to edit previous commands you entered in
 Command Window.
 • Insert " % " before the statement that you want to use it as comment; the statement
 will appear in green color.
 3
Experiment No. (1) Introduction to MATLAB
Now Try to do the following:
>> a=3
>> a=3; can you see the effect of semicolon " ; "
>> a+5 assign the sum of a and 5 to ans
>> b=a+5 assign the sum of a and 5 to b
>> clear a
>> a can you see the effect of clear command
>> clc clean the screen
>> b
Exercises
 1- Use edit command to edit the dct function, then try to edit sin function. State the
 difference.
 2- Use help command to get help about rand function.
 3- Enter a=3; b=5; c=7, then clear the variable b only
 4
 Experiment No. ( 2 )
 Working with Matrices
2-1 Entering Matrix
 The best way for you to get started with MATLAB is to learn how to handle matrices.
You only have to follow a few basic conventions:
 • Separate the elements of a row with blanks or commas.
 • Use a semicolon ( ; ) to indicate the end of each row.
 • Surround the entire list of elements with square brackets, [ ].
 For Example
 >> A = [16 3 2 13; 5 10 11 8; 9 6 7 12; 4 15 14 1]
 MATLAB displays the matrix you just entered.
 A =
 16 3 2 13
 5 10 11 8
 9 6 7 12
 4 15 14 1
 Once you have entered the matrix, it is automatically remembered in the MATLAB
workspace. You can refer to it simply as A. Also you can enter and change the values of
matrix elements by using workspace window.
2-2 Subscripts
 The element in row i and column j of A is denoted by A(i,j). For example, A(4,2)
is the number in the fourth row and second column. For the above matrix, A(4,2) is 15.
So to compute the sum of the elements in the fourth column of A, type
 >> A(1,4) + A(2,4) + A(3,4) + A(4,4)
 ans =
 34
 5
Experiment No. (2) Working with Matrices
You can do the above summation, in simple way by using sum command.
 If you try to use the value of an element outside of the matrix, it is an error.
 >> t = A(4,5)
 ??? Index exceeds matrix dimensions.
 On the other hand, if you store a value in an element outside of the matrix, the size
increases to accommodate the newcomer. The initial values of other new elements are zeros.
 >> X = A;
 >> X(4,5) = 17
 X =
 16 3 2 13 0
 5 10 11 8 0
 9 6 7 12 0
 4 15 14 1 17
2-3 Colon Operator
 The colon " : " is one of the most important MATLAB operators. It occurs in several
different forms. The expression
 >> 1:10
 is a row vector containing the integers from 1 to 10
 1 2 3 4 5 6 7 8 9 10
 To obtain nonunit spacing, specify an increment. For example,
 >> 100:-7:50
 100 93 86 79 72 65 58 51
 Subscript expressions involving colons refer to portions of a matrix.
 >>A(1:k,j)
 is the first k elements of the jth column of A.
 6
Experiment No. (2) Working with Matrices
 The colon by itself refers to all the elements in a row or column of a matrix and the
keyword end refers to the last row or column. So
 >> A(4,:) or >> A(4,1:end) give the same action
 ans =
 4 15 14 1
 >> A(2,end)
 ans =
 8
2-4 Basic Matrix Functions
 Command Description
 sum(x) The sum of the elements of x. For matrices,
 >> x=[1 2 3 sum(x) is a row vector with the sum over
 4 5 6]; each column.
 >> sum(x)
 ans =
 5 7 9
 >> sum(x,2) sum (x,dim) sums along the dimension dim.
 ans=
 6
 15
 >>sum(sum(x)) In order to find the sum of elements that are
 ans = stored in matrix with n dimensions, you must
 21 use sum command n times in cascade form,
 this is also applicable for max, min, prod,
 mean, median commands.
 7
Experiment No. (2) Working with Matrices
 Command Description
 mean(x) The average of the elements of x. For
 x=[1 2 3; 4 5 6]; matrices, mean(x) is a row vector with the
 >> mean(x) average over each column.
 ans = mean (x,dim) averages along the dimension
 2.5 3.5 4.5 dim.
 >> mean(x,2)
 ans =
 2
 5
 >>mean(mean(x))
 ans =
 3.5000
 zeros(N) Produce N by N matrix of zeros.
 zeros(N,M) Produce N by M matrix of zeros.
 >> zeros(2,3)
 ans =
 0 0 0
 0 0 0
 ones(N) Produce N by N matrix of ones.
 ones(N,M) Produce N by M matrix of ones.
 >> ones(2,3)
 ans =
 1 1 1
 1 1 1
 8
Experiment No. (2) Working with Matrices
 Command Description
 size(x) return the size (dimensions) of matrix x.
 >> x=[1 2 3
 4 5 6];
 >> size(x)
 ans =
 2 3
 length(v) return the length (number of elements)
 >> v=[1 2 3]; of vector v.
 >> length(v)
 ans =
 3
 single quote ( ' ) Matrix transpose. It flips a matrix about its
 main diagonal and it turns a row vector into a
 column vector.
 >> x=[1 2 3
 4 5 6
 7 8 9];
 >> x'
 ans =
 1 4 7
 2 5 8
 3 6 9
 >> v=[1 2 3];
 >> v'
 ans =
 1
 2
 3
 9
Experiment No. (2) Working with Matrices
 Command Description
 max (x) Find the largest element in a matrix or a
 >> x=[1 2 3 vector.
 4 5 6];
 >> max (x)
 ans =
 4 5 6
 >> max(max(x))
 ans =
 6
 min (x) Find the smallest element in a matrix or a
 >> x=[1 2 3 vector.
 4 5 6];
 >> min (x)
 ans =
 1 2 3
 >> min(min(x))
 ans =
 1
 magic(N) produce N Magic square. This command
 >> magic(3) produces valid magic squares for all N>0
 except N=2.
 ans =
 8 1 6
 3 5 7
 4 9 2
 10
Experiment No. (2) Working with Matrices
 Command Description
 inv(x) produce the inverse of matrix x.
 >> x=[1 4;
 5 8];
 >> inv(x)
 ans =
 -0.6667 0.3333
 0.4167 -0.0833
 diag(x) Return the diagonal of matrix x. if x is a
 >> x=[1 2 3 vector then this command produce a diagonal
 matrix with diagonal x.
 4 5 6
 7 8 9];
 >> diag(x)
 ans =
 1
 5
 9
 >> v=[1 2 3];
 >> diag(v)
 ans =
 1 0 0
 0 2 0
 0 0 3
 prod(x) Product of the elements of x. For matrices,
 >> x=[1 2 3 Prod(x) is a row vector with the product over
 each column.
 4 5 6];
 >> prod(x)
 ans = 4 10 18
 11
Experiment No. (2) Working with Matrices
 Command Description
 >> prod(prod(x))
 ans =
 720
 median(x) The median value of the elements of x. For
 x=[4 6 8 matrices, median (x) is a row vector with the
 10 9 1 median value for each column.
 8 2 5];
 >> median(x)
 ans =
 8 6 5
 >> median(x,2) median(x,dim) takes the median along the
 ans = dimension dim of x.
 6
 9
 5
 >> median(median(x))
 ans =
 6
Note
 When we are taken away from the world of linear algebra, matrices become
two-dimensional numeric arrays. Arithmetic operations on arrays are done
element-by-element. This means that addition and subtraction are the same for arrays and
matrices, but that multiplicative operations are different. MATLAB uses a dot ( . ),
or decimal point, as part of the notation for multiplicative array operations.
 12
Experiment No. (2) Working with Matrices
Example: Find the factorial of 5
 >> x=2:5;
 >> prod(x)
Example: if x = [1,5,7,9,13,20,6,7,8], then
 a) replace the first five elements of vector x with its maximum value.
 b) reshape this vector into a 3 x 3 matrix.
solution
 a)
 >> x(1:5)=max(x)
 b)
 >> y(1,:)=x(1:3);
 >> y(2,:)=x(4:6);
 >> y(3,:)=x(7:9);
 >> y
Example: Generate the following row vector b=[1, 2, 3, 4, 5, . . . . . . . . . 9,10],
 then transpose it to column vector.
solution
 >> b=1:10
 b =
 1 2 3 4 5 6 7 8 9 10
 >> b=b';
Exercises
 1- If x=[1 4; 8 3], find :
 a) the inverse matrix of x .
 b) the diagonal of x.
 c) the sum of each column and the sum of whole matrix x.
 d) the transpose of x.
 13
Experiment No. (2) Working with Matrices
 2- If x= [2 8 5; 9 7 1], b=[2 4 5] find:
 a) find the maximum and minimum of x.
 b) find median value over each row of x.
 c) add the vector b as a third row to x.
 3- If x=[ 2 6 12; 15 6 3; 10 11 1], then
 a) replace the first row elements of matrix x with its average value.
 b) reshape this matrix into row vector.
 4- Generate a 4 x 4 Identity matrix.
 5- Generate the following row vector b=[5, 10, 15, 20 . . . . . . . . . 95, 100], then find the
 number of elements in this vector.
 14
 Experiment No. ( 3 )
 Expressions
 Like most other programming languages, MATLAB provides mathematical
expressions, but unlike most programming languages, these expressions involve entire
matrices. The building blocks of expressions are:
 1- Variable 2- Numbers 3- Operators 4- Functions
3-1 Variable
 MATLAB does not require any type declarations or dimension statements. When
MATLAB encounters a new variable name, it automatically creates the variable and allocates
the appropriate amount of storage. If the variable already exists, MATLAB changes its
contents and, if necessary, allocates new storage. For example,
 num_students = 25
creates a 1-by-1 matrix named num_students and stores the value 25 in its
single element.
 Variable names consist of a letter, followed by any number of letters, digits, or
underscores. MATLAB uses only the first 31 characters of a variable name. MATLAB is
case sensitive; it distinguishes between uppercase and lowercase letters. A and a are not the
same variable.
3-2 Numbers
 MATLAB uses conventional decimal notation, with an optional decimal point and
leading plus or minus sign, for numbers. Scientific notation uses the letter ( e ) to specify a
power-of-ten scale factor. Imaginary numbers use either i or j as a suffix. Some examples of
legal numbers are
 3 -99 0.0001 9.6397238 1.60210e-20
 6.02252e23 1i 3+5j
 15
Experiment No. (3) Expressions
3-3 Arithmetic Operators
 Operator Description
 + Plus
 - Minus
 * Matrix multiply
 .* Array multiply
 ^ Matrix power
 .^ Array power
 \ Backslash or left matrix divide
 / Slash or right matrix divide
 .\ Left array divide
 ./ Right array divide
 () Specify evaluation order
3-4 Function
 MATLAB provides a large number of standard elementary mathematical functions,
including abs, sqrt, exp, and sin. Taking the square root or logarithm of a negative number is
not an error; the appropriate complex result is produced automatically. MATLAB also
provides many more advanced mathematical functions, including Bessel and gamma
functions. Most of these functions accept complex arguments. For a list of the elementary
mathematical functions, type
 >> help elfun
For a list of more advanced mathematical and matrix functions, type
 >> help specfun
 >> help elmat
 Some of the functions, like sqrt and sin, are built in. They are part of the MATLAB
core so they are very efficient, but the computational details are not readily accessible. Other
 16
Experiment No. (3) Expressions
functions, like gamma and sinh, are implemented in M-files. You can see the code and even
modify it if you want.
 Command Description
 abs(x) Absolute value (magnitude of complex number).
 acos(x) Inverse cosine.
 angle(x) Phase angle (angle of complex number).
 asin(x) Inverse sine.
 atan(x) Inverse tangent.
 atan2(x,y) Four quadrant inverse tangent: tan-1 (x / y).
 ceil(x) Round towards plus infinity.
 conj(x) Complex conjugate.
 cos(x) Cosine of x, assumes radians.
 exp(x) Exponential: e x.
 fix(x) Round towards zero.
 floor(x) Round towards minus infinity.
 imag(x) Complex imaginary part.
 log(x) Natural logarithm: ln(x).
 log10(x) Common (base 10) logarithm: log10(x).
 log2(x) Base 2 logarithm: log2(x).
 real(x) Complex real part.
 rem(x) Remainder after division.
 round(x) Round towards nearest integer.
 sign(x) Signum: return sign of argument.
 sin(x) Sine of x, assumes radians.
 sqrt(x) Square root.
 tan(x) Tangent of x, assumes radians.
 17
Experiment No. (3) Expressions
 Several special functions provide values of useful constants.
 Constant Description
 eps Floating point relative accuracy ≈ 2.2204e-016.
 realmax Largest positive floating point number.
 realmin Smallest positive floating point number.
 pi 3.1415926535897....
 i and j Imaginary unit − 1 .
 inf Infinity, e.g. 1/0
 NaN Not A Number, e.g. 0/0
3-5 Examples of Expressions
 1) >> x = (1+sqrt(5))/2
 x =
 1.6180
 >> a = abs(3+4i)
 a =
 5
 >> y=sin(pi/3)+cos(pi/4)-2*sqrt(3)
 y =
 -1.8910
 2) Solve the following system
 x+y=1
 x-y+z=0
 x+y+z=2
 Solution
 >> a=[1 1 0; 1 -1 1; 1 1 1]; b=[1;0;2];
 >> x=inv(a)*b
 or
 >> x=a\b
 18
Experiment No. (3) Expressions
Exercises
 1- Write a MATLAB program to calculate the following expression and round the
 answers to the nearest integer.
 a) z = 5x 2 + y 2 where x=2, y=4
 b) z = 4cos(x) + j6sin(x) where x=π/4
 c) z = 3sin( x) + 4cos(x) + 3e y where x=π/3 , y=2
 d) y =sin( x) / x where 0 ≤ x ≤ 2π
 2- Solve the following system
 x + y - 2z = 3
 2x + y = 7
 x+y-z=4
 3- Use [ round, fix, ceil, floor ] commands to round the following numbers towards
 integer numbers:
 Before After
 1.3 1
 1.5 1
 1.9 2
 11.9 11
 -2.9 -2
 -3.9 -4
 3.4 3
 4- Write a Program to calculate the electromagnetic force between two electrons placed
 (in vacuum) at a distance ( r = 2*10-13 m ) from each other. Charge of electron (Q) is
 1.6*10-19 C.
 Hint
 Q1Q 2
 Electromagnetic Force = K
 r2
 K=9*109
 19
 Experiment No. ( 4 )
 Input / Output of Variables
 ( Numbers and Strings )
4-1 Characters and Text
 Enter text into MATLAB using single quotes. For example,
 >> S = 'Hello'
 The result is not the same kind of numeric matrix or array we have been dealing with
up to now. The string is actually a vector whose components are the numeric codes for the
characters (the first 127 codes in ASCII). The length of S is the number of characters. It is a
1-by-5 character array. A quote within the string is indicated by two quotes.
 Concatenation with square brackets joins text variables together into larger strings. For
example,
 >> h = ['MAT', 'LAB']
joins the strings horizontally and produces
 h =
 MATLAB
and the statement
 >> v = ['MAT'; 'LAB']
joins the strings vertically and produces
 v =
 MAT
 LAB
 Note that both words in v have to have the same length. The resulting arrays are both
character arrays; h is 1-by-6 and v is 2-by-3.
4-1-1 Some String Function
 Function Description
 char (x) converts the array x that contains
 positive integers representing
 >> char(100) character codes into a MATLAB
 ans = character array (the first 127 codes
 d in ASCII).
 >> char([73 82 65 81])
 ans =
 IRAQ
 20
Experiment No. (4) Input / Output of Variables
 Function Description
 double(s) converts the character array to a
 numeric matrix containing floating
 >> double('z') point representations of the ASCII
 ans = codes for each character.
 122
 >> double('ali')
 ans =
 97 108 105
 strcat(S1,S2,...) joins S1,S2,...variables horizontally
 together into larger string.
 >>strcat('Hello',' Ali')
 ans =
 Hello Ali
 strvcat(S1,S2,...) joins S1,S2,... variables vertically
 together into larger string.
 >> strvcat ('Hello', 'Hi', 'Bye')
 ans =
 Hello
 Hi
 Bye
 s = num2str(x) converts the variable x into a string
 representation s.
 >> num2str(20)
 ans =
 20 % as a string,
 not a number
 x = str2num(s) converts character array
 representation of a matrix of
 >> str2num('20') numbers to a numeric matrix.
 ans =
 20
 error (Msg) displays the error message in the
 string (Msg), and causes an error
 exit from the currently executing
 M-file to the keyboard.
 21
Experiment No. (4) Input / Output of Variables
Note
 The printable characters in the basic ASCII character set are represented by the integers
32:127. (The integers less than 32 represent nonprintable control characters). Try
 >> char(33:127)
4-2 Input of Variable
 • To enter matrix or vector or single element:
 >> x=input('parameter= ')
 parameter= 2
 x =
 2
 >> x=input('parameter= ')
 parameter= [2 4 6]
 x =
 2 4 6
 >> x=input('parameter= ')
 parameter= [1 2 3;4 5 6]
 x =
 1 2 3
 4 5 6
 • To enter text:
 >> x=input('parameter= ')
 parameter= 'faaz'
 x = Notice the difference
 faaz between the two
 statements
 >> x=input('parameter= ' , 's' )
 parameter= faaz
 x =
 faaz
 22
Experiment No. (4) Input / Output of Variables
4-3 Output of Variable
 • disp ( x )
 displays the array ( x ), without printing the array name. In all other ways
it's the same as leaving the semicolon off an expression except that empty arrays don't
display.
 If ( x ) is a string, the text is displayed.
 >> x=[1 2 3];
 >> x
 x =
 1 2 3
 >> disp(x)
 1 2 3
Example:
>> a=6;
>> b=a;
>> s='Ahmed has ';
>> w='Ali has ';
>> t=' Dinars';
>>disp([ s num2str(a) t]);
>>disp([ w num2str(b) t]);
the execution result is:
Ahmed has 6 Dinars
Ali has 6 Dinars
4-4 M-File:
 An M-File is an external file that contains a sequence of MATLAB statements.
 By typing the filename in the Command Window, subsequent MATLAB input is
 obtained from the file. M-Files have a filename extension of " .m " and can be created
 or modified by using Editor/Debugger Window.
 23
Experiment No. (4) Input / Output of Variables
Exercises:
 1- If x=[1 5 9; 2 7 4], then
 a) display the last two elements by using disp command.
 b) display the sum of each row as show below
 The sum of 1st row =
 The sum of 2nd row =
 2- Write a program in M-File to read 3 x 3 Matrix, then display the diagonal of matrix as
 shown below:
 The Diagonal of This Matrix = [ ]
 3- Write a program to read a string, then replace each character in the string with its
 following character in ASCII code*.
 4- The Table shown below lists the degrees of three students, Write a program in M-file
 to read these degrees and calculate the average degree for each student.
 Name Mathematics Electric Circuits Communication
 Ahmed 80 80 80
 Waleed 75 80 70
 Hasan 80 90 85
 Then display results as shown below
 Name Degree
 -----------------------------
 Ahmed 80
 Waleed 75
 Hasan 85
* This operation is called Caesar cipher.
 24
 Experiment No. ( 5 )
 Relational and Logical Operations
 These operations and functions provide answers to True-False questions. One
important use of this capability is to control the flow or order of execution of a series of
MATLAB commands (usually in an M-file ) based on the results of true/false questions.
 As inputs to all relational and logical expressions, MATLAB considers any nonzero
number to be true, and zero to be False. The output of all relational and logical expressions
produces one for True and zero for False, and the array is flagged as logical. That is, the
result contains numerical values 1 and 0 that can be used in mathematical statement, but also
allow logical array addressing.
5-1 Relational Operations
 Operation Description
 == Equal
 ~= Not equal
 < Less than
 > Greater than
 <= Less than or equal
 >= Greater than or equal
Example:
>> a=1:9; b=9-a;
>> t=a>4 %finds elements of (a) that are greater than 4.
t =
 0 0 0 0 1 1 1 1 1
Zeros appear where a ≤ 4, and ones where a > 4.
 25
Experiment No. (5) Relational and Logical Operations
>> t= (a==b) %finds elements of (a) that are equal to those in (b).
t =
 0 0 0 0 0 0 0 0 0
5-2 Logical Operation
 Operation Description
 & Logical AND
 | Logical OR
 ~ Logical NOT
 xor (a,b) Logical EXCLUSIVE OR
Example:
>> a = [0 4 0 -3 -5 2];
>> b = ~a
b =
 1 0 1 0 0 0
>> c=a&b
c =
 0 0 0 0 0 0
Example: let x=[ 2 -3 5 ;0 11 0], then
 a) find elements in x that are greater than 2
 b) find the number of nonzero elements in x
solution
 a)
 >> x>2
 ans =
 0 0 1
 0 1 0
 26
Experiment No. (5) Relational and Logical Operations
 b)
 >> t=~(~x);
 >> sum(sum(t))
 ans =
Exercises
 1- write a program to read three bits x, y, z, then compute:
 a) v = (x and y) or z
 b) w = not (x or y) and z
 c) u = (x and not (y)) or (not (x) and y)
 2- Write a program for three bits parity generator using even-parity bit.
 3- Write a program to convert a three bits binary number into its equivalent gray code.
 4- if q=[1 5 6 8 3 2 4 5 9 10 1],x=[ 3 5 7 8 3 1 2 4 11 5 9],
 then:
 a) find elements of (q) that are greater than 4.
 b) find elements of (q) that are equal to those in (x).
 c) find elements of (x) that are less than or equal to 7.
 5- If x=[10 3 ; 9 15], y=[10 0; 9 3], z=[-1 0; -3 2], what is the
 output of the following statements:
 a) v = x > y
 b) w = z >= y
 c) u = ~z & y
 d) t = x & y < z
 27
 Experiment No. ( 6 )
 Flow Control
 Computer programming languages offer features that allow you to control the flow of
command execution based on decision making structures. MATLAB has several flow control
constructions:
 • if statement.
 • switch and case statement.
 • for statement.
 • while statement.
 • break statement.
6-1 if statement
 The if statement evaluates a logical expression and executes a group of statements
when the expression is true. The optional elseif and else keywords provide for the execution
of alternate groups of statements. An end keyword, which matches the if, terminates the last
group of statements.
 The general form of if statement is:
 if expression 1
 group of statements 1
 elseif expression 2
 group of statements 2
 else expression 3
 group of statements 3
 end
 It is important to understand how relational operators and if statements work with
matrices. When you want to check for equality between two variables, you might use
 if A = = B
 This is legal MATLAB code, and does what you expect when A and B are scalars. But
when A and B are matrices, A = = B does not test if they are equal, it tests Where they are
 28
Experiment No. (6) Flow Control
equal; the result is another matrix of 0’s and 1’s showing element-by-element equality.
In fact, if A and B are not the same size, then A = = B is an error. The proper way to check
for equality between two matrix is to use the isequal function,
 if isequal(A,B)
Example:
 A=input('A=');
 B=input('B=');
 if A > B
 'greater'
 elseif A < B
 'less'
 elseif A == B
 'equal'
 else
 error ('Unexpected situation')
 end
6-2 switch and case statement
 The switch statement executes groups of statements based on the value of a variable or
expression. The keywords case and otherwise delineate the groups. Only the first matching
case is executed. There must always be an end to match the switch. If the first case statement
is true, the other case statements do not execute.
 The general form of switch statement is:
 switch expression
 case 0
 statements 0
 case 1
 statements 1
 otherwise
 statements 3
 end
 29
Experiment No. (6) Flow Control
Example
 method = 'Bilinear';
 switch lower(method)
 case 'bilinear'
 disp('Method is bilinear')
 case 'cubic'
 disp('Method is cubic')
 case 'nearest'
 disp('Method is nearest')
 otherwise
 disp('Unknown method.')
 end
 Execution result is:
 Method is bilinear
Hint
 • lower(a) command: converts any upper case characters in ( a ) to the
 corresponding lower case character and leaves all other characters unchanged.
 • upper(a) command: converts any lower case characters in ( a ) to the
 corresponding upper case character and leaves all other characters unchanged.
6-3 for statement
 The for loop repeats a group of statements a fixed, predetermined number of times.
 The general form of for statement is:
 for variable = initial value: step size: final value
 statement
 . . .
 statement
 end
 30
Experiment No. (6) Flow Control
Example:
 for i=1:5
 for k=5:-1:1
 m(i,k)=i*k;
 end
 end
 >> m
 m =
 1 2 3 4 5
 2 4 6 8 10
 3 6 9 12 15
 4 8 12 16 20
 5 10 15 20 25
 A for loop cannot be terminated by reassigning the loop variable within the for loop:
 for i=1:10
 x(i)=sin (pi/i);
 i=10; % this step do not effect on the for loop
 end
 x
 i
Execution results are,
x=
 0.0000 1.0000 0.8660 0.7071 0.5878 0.5000
 0.4339 0.3827 0.3420 0.3090
i=
 10
6-4 while statement
 repeat statements an indefinite number of times under control of a logical condition.
A matching end delineates the statements.
 31
Experiment No. (6) Flow Control
 The general form of while statement is:
 while expression
 statement
 ...
 statement
 end
Example: Here is a complete program, illustrating while, if, else, and end, that
 uses interval bisection method to find a zero of a polynomial.
 a = 0; fa = -Inf;
 b = 3; fb = Inf;
 while b-a > eps*b
 x = (a+b)/2;
 fx = x^3-2*x-5;
 if sign(fx) == sign(fa)
 a = x; fa = fx;
 else
 b = x; fb = fx;
 end
 end
6-5 break
 Terminate execution of while or for loop. In nested loops, break exits from the
innermost loop only. If break is executed in an IF, SWITCH-CASE statement, it terminates
the statement at that point.
Example:
we can modify the previous example by using break command.
 a = 0; fa = -Inf;
 b = 3; fb = Inf;
 while b-a > eps*b
 x = (a+b)/2;
 fx = x^3-2*x-5;
 32
Experiment No. (6) Flow Control
 if fx == 0
 break
 elseif sign(fx) == sign(fa)
 a = x; fa = fx;
 else
 b = x; fb = fx;
 end
 end
Example: Without using the max command, find the maximum value of matrix (a) where
 a =[11 3 14;8 6 2;10 13 1]
Solution
 a=[11 3 14;8 6 2;10 13 1]
 temp=a(1);
 [n,m]=size(a);
 for i=1:n
 for j=1:m
 if a(i,j)>temp
 temp=a(i,j);
 end
 end
 end
 temp
the execution result is 14
Example: Let x=[2 6; 1 8], y=[.8 -0.3 ; -0.1 0.2], prove that y is not the inverse matrix of x.
Solution
 z=inv(x);
 if ~isequal(z,y)
 disp(' y is not the inverse matrix of x ')
 end
the execution result is
 y is not the inverse matrix of x
 33
Experiment No. (6) Flow Control
Exercises
 1- The value of s could be calculated from the equation below:
 y 2 − 4 xz if y ≥ 4xz
 s=
 inf if y < 4xz
 write a MATLAB program in M-File to do the following steps:-
 a) input the value of x, y, z
 b) caluclate s
 c) print the output as shown below
 x=...
 y=...
 z=...
 s=...
 2- Write a program to find the current I in the circuit shown below
 a) By using conditional statements.
 b) Without using any conditional statements.
 I R1= 2.5 Ω Switch
 V= 5 volt
 R2= 5 Ω
 R3= 5
 Ω
 3- Write a group of statements that carry out the same action of upper and lower
 functions.
 34
 Experiment No. ( 7 )
 Plotting Function
 MATLAB has extensive facilities for displaying vectors and matrices as graphs,
as well as annotating and printing these graphs.
7-1 Creating a Plot using plot function
 The plot function has different forms, depending on the input arguments. If y is a
vector, plot(y) produces a piecewise linear graph of the elements of y versus the index of the
elements of y. If you specify two vectors as arguments, plot(x,y) produces a graph of
y versus x. For example, these statements use the colon operator to create a vector of x values
ranging from zero to 2*pi, compute the sine of these values, and plot the result.
 x = 0:pi/100:2*pi;
 y = sin(x);
 plot(y)
 35
Experiment No. (7) Plotting Function
Now plot y variable by using:
 plot(x,y)
can you see the difference at x-axis
7-2 Specifying Line Styles and Colors
 Various line types, plot symbols and colors may be obtained with plot(x,y,s) where s is
a character string made from one element from any or all the following 3 columns:
 Color Marker Line Style
 b blue . point - solid
 g green o circle : dotted
 r red x x-mark -. dashdot
 c cyan + plus -- dashed
 m magenta * star (none) no line
 y yellow s square
 k black d diamond
 v triangle (down(
 < triangle (left)
 p pentagram
 h hexagram
 36
Experiment No. (7) Plotting Function
Example:
 x1 = 0:pi/100:2*pi;
 x2 = 0:pi/10:2*pi;
 plot(x1,sin(x1),'r:',x2,cos(x2),'r+')
7-3 Adding Plots to an Existing Graph
 The hold command enables you to add plots to an existing graph. When you type
 hold on MATLAB does not replace the existing graph when you issue another plotting
command; it adds the new data to the current graph, rescaling the axes if necessary.
Example:
 x1 = 0:pi/100:2*pi;
 x2 = 0:pi/10:2*pi;
 plot(x1,sin(x1),'r:')
 hold on
 plot(x2,cos(x2),'r+')
 37
Experiment No. (7) Plotting Function
7-4 Multiple Plots in One Figure
 The subplot command enables you to display multiple plots in the same window or
print them on the same piece of paper. Typing
 subplot(m,n,p)
partitions the figure window into an m-by-n matrix of small subplots and selects the pth
subplot for the current plot. The plots are numbered along first the top row of the figure
window, then the second row, and so on. For example, these statements plot data in four
different sub regions of the figure window.
 t = 0:pi/10:2*pi;
 x=sin(t); y=cos(t); z= 2*y-3*x; v=5-z;
 subplot(2,2,1); plot(x)
 subplot(2,2,2); plot(y)
 subplot(2,2,3); plot(z)
 subplot(2,2,4); plot(v)
 38
Experiment No. (7) Plotting Function
7-5 Setting Axis Limits
 By default, MATLAB finds the maxima and minima of the data to choose the axis
limits to span this range. The axis command enables you to specify your own limits
axis([xmin xmax ymin ymax])
7-6 Axis Labels and Titles
The xlabel, ylabel, and zlabel commands add x-, y-, and z-axis labels. The title command
adds a title at the top of the figure and the text function inserts text anywhere in the figure.
Example:
 t = -pi:pi/100:pi;
 y = sin(t);
 plot(t,y)
 axis([-pi pi -1 1])
 xlabel('x-axis')
 39
Experiment No. (7) Plotting Function
 ylabel('sin(t)')
 title('Graph of the sine function')
 text(1,-1/3,'Note the odd symmetry')
Exercises
 1- Plot sawtooth waveform as shown below
 2- Plot Sinc function, where Sinc (x) = sin(x) / x , and -2π ≤ x ≤ 2π
 3- Plot sin(x) and cos(x) on the same figure, then on the same axis using different colors.
 40
 Experiment No. (7) Plotting Function
 4- if y=sin(x), z=cos(x), v=exp(x), where -π ≤ x ≤ π
 could you plot y, z, v as shown below!
 41
View publication stats