ELE 562 NOTE (Part 1 and Tutorial Questions) - 2
ELE 562 NOTE (Part 1 and Tutorial Questions) - 2
MATLAB
MATLAB stands for MATrix LABoratory and it was originally developed by Cleve Moler in the 1970‘s.
MATLAB is a programming language that provides a numerical computing environment and a suite of tools for
computation, visualization, and more.
A command interface created for interactive management plus a simple integration of particular functions,
programs, and libraries supports the operation of MATLAB.
MATLAB is an interpreter language and its commands can be carried out directly. The statements are translated
into machine code one by one by MATLAB‘s interpreter. In comparison, a compiled programming language like
C has a program translated as a whole into machine code by the compiler.
A typical MATLAB desktop which provides an interface for the MATLAB user is illustrated in Fig. 1
Title bar Desktop toolbar Workspace
Menu bar Command window
Command history
1
The MATLAB desktop comprises the Title bar, Menu bar, Desktop toolbar, Command window, Command
history, Current directory, and Workspace panels.
(1) Title bar: The title bar contains the program‘s name and logo as well as the window control buttons. It is
situated on the top of the main MATLAB window.
(2) Menu bar: The menu bar is underneath the title bar. It has commands for opening, closing files, preferences,
etc.
(3) Desktop toolbar: The desktop toolbar is placed underneath the menu bar. It contains many items found on
the menus, new file, open, copy, paste, etc.
(4) Command window: The command window is the most important part of the MATLAB main desktop. It is
the window where input and output appears. In this window the user can enter commands and obtain results.
Each new line on the command prompt starts with the symbol ―>>‖. This defines where new input can be
entered.
(5) Command history: The command history window contains the history of the commands entered in the
command window. It begins on each new session with the starting date and time. Thus each session history is
separated by dates.
(6) Current folder: On the top of this window there is box, which contains the location of the current directory,
same as the one in the desktop toolbar. File names appear on the left column, file types on the middle and last
date of modification on the right column.
(7) Workspace: This window displays the loaded variables of the current MATLAB session, these are variables
you have created and are currently loaded on the memory. It displays their name, their size, that is their
dimensions, the number of bytes they take on memory and their class, that is the type of variable.
2
visible in the Current Folder window), then at the command prompt in the command window, one may
type the following command in order to invoke this script m-file (see Fig. 3.2):
>> addition
Note that in Fig. 3.1, the semicolons on the 1st, 2nd, and 3rd lines suppress MATLAB from printing the
result of the commands. Also note that the 4th line of Fig. 3.1 does not have a semicolon which makes its
result to be printed on screen as shown in Fig. 3.2
Editor window
Lines of code in a script-m file Command window
Result
Fig. 3.2 Invoking the code in the saved script m-file. Note that
Fig. 3.1 A script m-file which has been saved with the file name the file name of the script m-file in this case is
―addition.m‖ which contains the code for adding the ―addition.m‖
numbers 1, 2, and 8
Result
3
In the above example, variables a=1, b=3, and c=8 are passed as input arguments to the addition function.
These values of a, b, and c are used in the function for computation after which the result is returned as
d=12.
Create an instance
Editor window of class addition Set the values of
Lines of code Command window members a, b,
and c
Call ―add‖
method
Result
Fig. 5.1 A class m-file which has been saved with the file name
―addition.m‖ which contains the method for adding any 3
numbers passed as argument to it
M-files are ordinary text files containing MATLAB commands. They are created or modified using any text
editor or word processor that is capable of saving files as plain ASCII text.
4
3. A MATLAB variable must not contain a space character
4. Variables names should not coincide with a predefined MATLAB command or with any user-defined
subroutines. To check whether a variable name is already in use we can use the command:
>> which variable_name
This command indicates whether or not the variable_name corresponds to an existing code or intrinsic
function.
Scalar arithmetic operators
A scalar variable is a variable that contains a single number. MATLAB uses the symbols +, -, *, /, ^ for addition,
subtraction, multiplication, division, and exponentiation (power) of scalars numbers as illustrated in Table 1.
Example 1
The following are computations executed by using the command window of MATLAB
>>6 + 2*9
ans = >>3^3 - 24 - 15/(3*5) >>(3*1)^4 + 7
24 ans = ans =
2 88
>>(1 + 7)*3
ans = >>3*5^2 + 9
24 >>64^(1/3) + 81^(0.25)
ans = ans =
>>3^2 + 6 - 9/3*5 84 7
ans =
0
5
Relational operators
Table 3 contains a list of the relational operators in MATLAB.
Table 3 Relational operators
Operator meaning
< Less than
<= Less than or equal to
>= Greater than or equal to
== Equal to
~= Not equal to
Logical operators
Table 4(a) lists the logical operators in MATLAB. Note that A and B are not considered purely as matrices but
as logical expressions. The truth table of these operators is illustrated in Table 4(b).
Table 4(a) Relational operators Table 4(b) Truth table of relational operators
Operator Function form Meaning A B A&B A|B xor(A,B) ~A
& and(A,B) AND 0 0 0 0 0 1
| or(A,B) Inclusive OR 1 0 0 1 1 0
xor(A,B) Exclusive OR 0 1 0 1 1 1
~ not(A) NOT 1 1 1 1 0 0
Predefined constants
MATLAB has several predefined special constants. For example pi represents π, while Inf stands for ∞. Some
other predefined constants are illustrated in Table 5.
Table 5 Predefined special constants
Predefined constant Description
ans Temporary variable containing the most recent answer
eps Specifies the accuracy of floating point precision.
i,j The imaginary unit √-1
Inf Infinity
NaN Indicates an undefined numerical result
pi The number π
Inf in practice means a number is so large that MATLAB cannot represent it. For example, typing 5/0 generates
the answer Inf.
The symbol NaN indicates an undefined numerical result such as that obtained by typing 0/0.
The symbol eps is the smallest number which, when added to 1 by the computer, creates a number greater than 1.
It is usually used as an indicator of the accuracy of computations.
The symbols i and j denote the imaginary unit, and they are used represent complex numbers, such as y = 7 + 2i
The use of these special constants as variable names should be avoided. Although MATLAB allows the
programmer to assign a different value to these constants, it is however not a good practice to do so
6
c1 = 1-2i.
or
c1 = complex(1, -2).
Note that an asterisk is not needed between i or j and a number, although it is required with a variable, such as
c2 = 5 - i*c1.
This convention can cause errors if care is not taken. For example, the expressions
y = 7/2*i
and
x =7/2i
give two different results which are:
y =(7/2)i = 3.5i
and
x = 7/(2i)= -3.5i
Addition, subtraction, multiplication, and division of complex numbers are easily done. For example,
>>w*s
ans =
78.0000 + 8.0000i
>>w/s
ans =
-0.8276 - 1.0690i
MATLAB comment
Comments are used to document programs and the symbol used for indicating comments in MATLAB is the
percent (%) symbol. Hence, MATLAB ignores everything on the right-hand side of the % symbol as they are
treated as comments.
Comments are categorized into two
(i) Single line comments: This category of comment spans only one line. MATLAB ignores everything to the
right of the ―%‖ symbol but executes everything to the left of it. For example
x = 1+2 % addition of numbers
(ii) Multiline comments: This category of comment spans more than one line. This is accomplished by placing
the comment statements in between the symbol pair ―%{‖ and ―%}‖. For example
x = 1+2;
y = 1-2;
%{
this program computes
the addition and subtraction
of two numbers
%}
7
The disp function (short for ―display‖) can be used to display the value of a variable but not its name. Its syntax
is disp(A), where A represents a MATLAB variable name. The disp function can also display text such as a
message to the user. Text is usually enclosed within single quotes. For example, the command
disp(‗The voltage = ‘)
causes the message ―The voltage is‖ to appear on the screen.
Formatting command
The format command controls how numbers appear on the screen. Table 7 gives the variants of this command.
MATLAB uses many significant figures in its calculations, but we rarely need to see all of them. The default
MATLAB display format is the short format, which uses four decimal digits. You can display more by typing
format long, which gives 16 digits. To return to the default mode, type format short. You can force the output to
be in scientific notation by typing format short e, or format long e, where e stands for the number 10. Thus the
output 6.3792e+03 stands for the number 6.3792 x103. The output 6.3792e-03 stands for 6.3792 x10-3
Formatting specifiers
The ―format‖ command is convenient for simple programs, but MATLAB provides a far more sophisticated way
for printing information by means of a function borrowed from the languages C and C++, called ―fprintf”.
―fprintf‖ stands for ―formatted printing to a file‖ and it requires at least one argument.
Its first argument is a format string, which is a string that specifies the way in which printing is to be done, such
as words that must be printed, spacing, the number of decimal places to be used for printing numbers, etc.
In the format string, the format of each value that is to be printed is specified individually. For example, one
value may be printed with four decimal places and another with nine. Additionally, any text that is to be printed
along with the values is included in the format string. Following the format string there are typically additional
8
input arguments to fprintf. These are the values that are to be printed and they must appear as arguments in the
order that they are to be printed. For example,
>>x=2; y = 3; z = x*y
>>fprintf('%d items at $%.2f\nTot = $%5.2f\n',x,y,z)
2 items at $3.00
Tot = $ 6.00
>>
In the example above, the %d, %.2f, and %5.2f are known as conversion characters. Instead of being printed, a
percent symbol, ―%‖, and the characters immediately after the percent symbol indicate to MATLAB that the
value of one argument after the format string, is to be printed in a specific format.
The meaning of the d in %d, for example, is "If the value is an integer, print it without a decimal point;
otherwise print it in scientific notation."
The f in %.2f is a format specifier, which is a character specifying the format in which an object is to be printed;
i.e., "Print using fixed-point notation‖
The 5 in the format %5.2f means "Print using at least five spaces.‖
9
Table 9 Mathematical functions
Command Description
Exponential
exp(x) Exponential; ex
sqrt(x) Square root; √x
Logarithmic
log(x) Natural logarithm; ln x
log10(x) Common (base-10) logarithm; log x = log10 x
log2(x) Base-2 logarithm of x
Complex
abs(x) Absolute value; x
angle(x) Angle of a complex number x
conj(x) Complex conjugate
imag(x) Imaginary part of a complex number x
real(x) Real part of a complex number x
Numeric
ceil(x) Round to the nearest integer toward ∞
fix(x) Round to the nearest integer toward zero
floor(x) Round to the nearest integer toward -∞
round(x) Round toward the nearest integer
sign(x) Signum function:
+1 if x > 0; 0 if x = 0; -1 if x < 0
Trigonometric
cos(x) Cosine; cos x
cot(x) Cotangent; cot x
csc(x) Cosecant; cosec x
sec(x) Secant; sec x
sin(x) Sine; sin x
tan(x) Tangent; tan x
Inverse trigonometric
acos(x) Inverse cosine; arccos x = cos-1 x
acot(x) Inverse cotangent; arccot x = cot-1 x
acsc(x) Inverse cosecant; arccsc x = csc-1 x
asec(x) Inverse secant; arcsec x = sec-1 x
asin(x) Inverse sine; arcsin x = sin-1 x
atan(x) Inverse tangent; arctan x = sec-1 x
Data types
Computers operate on bits, but humans think in terms of numbers, words, and other types of data. Like any good
language, MATLAB organizes bits into convenient data types.
10
Most of the time, a MATLAB programmer need not be concerned with the specifics of the types of numbers
used in a calculation. The benefit derived in selecting an appropriate data type for a variable is that it saves
memory space—in some cases a lot of it—because types with narrower ranges can be stored in fewer bytes.
To determine the data type of a MATLAB variable, the function ―class” is used. For example,
>> x = 14;
>> class(x)
ans =
double
The word int embedded in all but two of the names means ―integer‖; a leading ―u” means unsigned, so uint
means ―unsigned integer‖.
MATLAB provides a set of functions that allow the user to check for a specific type. The name of each function
begins with ―is‖. Examples include isinteger, isfloat, issingle, isnumeric, and ischar.
Each of these functions takes an array as an input argument and returns either true or false. The name of the
function reveals its meaning: isinteger(x) returns true if and only if x is of one of the integer types.
The data type of a variable can be converted to another data type, for example
11
>> x = 10
x=
10
>> class(x)
ans =
double
>> x = int8(10)
x=
10
>> class(x)
ans =
int8
If a conversion function is given a value outside its range, it will return the value that lies at the closest end of its
range. For example,
>> int8(128)
ans =
127
>> int8(-1000)
ans =
-128
The sequence of numbers that encode a string is stored as a standard row >> course = ‗ELE 562‘;
vector. The length of the vector is equal to the number of characters in it. For example >> length(course)
ans =
Each individual element of a string can be accessed using an indexing scheme. 7
For example
>> course = ‗ELE 562‘;
>> course(1)
ans =
E
>> course (1:3)
ans =
ELE
>> course (5:7)
ans =
562
12
One of the schemes used for encoding characters as numbers is shown in Table 11. This encoding scheme is
called ASCII (American Standard Code for Information Interchange)
Table 11 ASCII code
Dec Char Dec Char Dec Char Dec Char Dec Char Dec Char Dec Char
0 NULL 20 DC4 40 ( 60 < 80 P 100 d 120 x
1 SOH 21 NAK 41 ) 61 = 81 Q 101 e 121 y
2 STX 22 SYN 42 * 62 > 82 R 102 f 122 z
3 ETX 23 ETB 43 + 63 ? 83 S 103 g 123 {
4 EOT 24 CAN 44 , 64 @ 84 T 104 h 124 |
5 ENQ 25 EM 45 - 65 A 85 U 105 i 125 }
6 ACK 26 SUB 46 . 66 B 86 V 106 j 126 ~
7 BEL 27 ESC 47 / 67 C 87 W 107 k 127 DEL
8 BS 28 FS 48 0 68 D 88 X 108 l
9 HT 29 GS 49 1 69 E 89 Y 109 m
10 LF 30 RS 50 2 70 F 90 Z 110 n
11 VT 31 US 51 3 71 G 91 [ 111 o
12 FF 32 52 4 72 H 92 \ 112 p
13 CR 33 ! 53 5 73 I 93 ] 113 q
14 SO 34 " 54 6 74 J 94 ^ 114 r
15 SI 35 # 55 7 75 K 95 _ 115 s
16 DLE 36 $ 56 8 76 L 96 ` 116 t
17 DC1 37 % 57 9 77 M 97 a 117 u
18 DC2 38 & 58 : 78 N 98 b 118 v
19 DC3 39 ' 59 ; 79 O 99 c 119 w
Note that spaces and punctuation marks are all part of the string, and each one is encoded with its own number.
The numeric value of a character can be obtained by using a conversion function. For example
13
(III) Cell data type
Cell arrays can hold multiple data types. It is possible for example to have a string, various types of matrices as
well as a cell array inside a cell array.
Cell arrays are constructed with the use of the curly brackets {}.
For example, supposing it is desired to construct a 2 x 2 cell array whose cell contains the student‘s name, matric
number, courses, and scores in test and exam. The cell array could be as follows:
ADE 13/30GC1000
ELE447 25 45
ELE562 22 50
For example
>>Student = {‗ADE‘, ‗13/30GC1000‘; {‗ELE447‘;‘ELE562‘}, [25,45; 22,50]}
Student =
‗ADE‘ ‗13/30GC1000‘
(2x1 cell) (2x2 cell)
Note that space or comma defines the next column and semicolon defines the next row.
To access a specific element of any data type inside a cell, an operator is placed immediately after curly brackets
e.g. if the cell element is an array or a string, round brackets () are used; if the cell element is another cell, curly
brackets {} are used.
For example
14
>>Student = {‗ADE‘, ‗13/30GC1000‘; {‗ELE447‘;‘ELE562‘}, [25,45; 22,50]};
>>Student{1,1}
ans =
‗ADE‘
>>Student{2,1}
ans =
{2x1 cell}
>>Student{2,1}{1}
ans =
‗ELE447‘
>>Student{2,1}{2}
ans =
‗ELE562‘
>>Student{2,2}(1,2)
ans =
45
>>Student{2,1}([1 2])
ans =
25 22
>>Student{2,1}([2 3 4])
ans =
22 45 50
(i) Cell indexing: on the left side of the cell assignment statement, the cell subscripts are enclosed in round
brackets, while on the right side, cell contents of the assignment statement are enclosed in curly brackets.
For example, consider the cell array:
ADE 13/30GC1000
ELE447 25 45
ELE562 22 50
Student(1,1) = {‗ADE‘}
Student(1,2) = {‗13/30GC1000‘}
Student(2,1) = {‗ELE447‘, ‗ELE562‘}
Student(2,2) = { [25,45; 22,50]}
(ii) Content indexing: on the left side of the cell assignment statement, the cell subscripts are enclosed in curly
brackets, then specify the cell contents on the right side of the assignment operator.
The cells can be assigned data values as follows:
15
Student{1,1} = ‗ADE‘
Student{1,2} = ‗13/30GC1000‘
Student{2,1} = {‗ELE447‘, ‗ELE562‘}
Student{2,2} = [25,45; 22,50]
Structs use the dot notation (.) to specify and to access the fields.
student.name = ‗ADE‘;
student.matric_no = ‗13/30GC1000‘;
student.email = ‗[email protected]‘;
student.age = 21;
The elements of the struct student can be viewed by typing the command:
>>student
16
For example
>>student
name: ‗ADE‘
matric_no : ‗13/30GC1000‘
email : ‗[email protected]‘
age: 21
To add a second student to the database, a subscript is enclosed in round brackets after the struct‘s name as
follows:
student(2).name = ‗CHIKE‘;
student(2).matric_no = ‗13/30GC1001‘;
student(2).email = ‗[email protected]‘;
student(2).age = 23;
>>student(2)
name: ‗CHIKE‘
matric_no : ‗13/30GC1001‘
email : ‗[email protected]‘
age: 23
For example
student=
name: ‗ADE‘
matric_no : ‗13/30GC1000‘
email : ‗[email protected]‘
age: 21
To delete a field from every struct in the array , use the rmfield function.
The syntax is:
array_name = rmfield(array_name, ‗field‘)
Assuming the email field is to be removed from the struct student, it can be achieved by typing :
student = rmfield(student, ‗email‘)
For example
17
>> student = rmfield(student, ‗email‘)
student=
name: ‗ADE‘
matric_no : ‗13/30GC1000‘
age: 21
Table 14 illustrates other functions that can be used with struct student and their descriptions
(I) Scalar: A scalar variable contains a single element and in MATLAB, it is treated as a 1x1 matrix. It is
entered without any brackets. For example
>>A = 10
A=
10
(II) Vector: A vector in MATLAB is simply a matrix with exactly one column or exactly one row. A variable
with exactly one column is called a column vector while a variable containing exactly one row is called a row
vector. Vectors in MATLAB are enclosed in square brackets. Consider the following vectors:
A 1 3 5
1
B 3
5
To enter row vector A and column vector B in MATLAB, one may type:
A = [1,3,5] or A = [1 3 5]
and
B = [1;3;5]
Note that a vector is entered by rows, with entries in a row separated by spaces or commas, and the rows
separated by semicolons. For example
18
>>A = [1,3,5]
A=
1 3 5
>>B = [1;3;5]
B=
1
3
5
The colon ―:" is one of the most useful operators in MATLAB. One of its usages is in the construction row
vectors with regularly spaced values. For example
>>A = 2:5
A=
2 3 4 5
If the spacing between the elements is not 1, then the spacing has to be stated. For example, if the spacing is 0.5
then, the previous expression is modified as follows
>>A = 2:0.5:5
A=
2 2.5 3 3.5 4 4.5 5
(III) Matrix: Scalars and vectors are regarded as special cases of matrices. A matrix is entered by rows, with
entries in a row separated by spaces or commas, and the rows separated by semicolons. The entire matrix is
enclosed in square brackets. Assuming a matrix A is a 3 by 2 matrix written as:
1 2
A 3 4
5 6
In MATLAB, matrix A is entered as:
A = [1,2,;3,4;5,6]
For example
>>A = [1,2;3,4;5,6]
A= 1 2
3 4
5 6
The default in MATLAB is that a matrix is printed in column-major order, meaning that all the elements of one
column are processed, before the elements of the next column.
19
Addressing matrices
Matrix indices are the row and column numbers of an element in a matrix and are used to keep track of the
matrix‘s elements. For example, the notation V(5) refers to the fifth element in the vector V, and A(2,3) refers to
the element in row 2, column 3 in the matrix A.
Note that
(i) the row number is always listed first!
(ii) indices always start at 1 and NOT at 0
To selects individual elements, rows, columns, or ―submatrix‖ of a matrix, the colon operator is used. Some
example in which the colon operator has been put to use are as follows:
■ V(:) represents all the row or column elements of the vector V.
■ V(2:5) represents the second through fifth elements; that is V(2), V(3), V(4), V(5).
■ A(:,3) denotes all the elements in the third column of the matrix A.
■ A(3,:) denotes all the elements in the third row of A.
■ A(:,2:5) denotes all the elements in the second through fifth columns of A.
■ A(2:3,1:3) denotes all the elements in the second and third rows that are also in the first through third
columns.
■ V = A(:) creates a vector V consisting of all the columns of A stacked from first to last.
■ A(end,:) denotes the last row in A, and A(:,end) denotes the last column.
To change the element at row 3, column 1 from its current value 5 to 20, one may type
>>A(3,1) = 20
A= 1 2 7 11
3 4 9 12
20 6 10 13
To get submatrix B which is equal to rows 2 and 3, and columns 2, 3, and 4 of matrix A, one can type
>> B = A([2 3],[2 3 4])
B=
4 9 12
6 10 13
Equivalent expressions for getting submatrix B include
>>B = A( 2:3 , 2:4 )
>>B = A( 2:3 , 2:end)
20
One may permute columns (or rows) simply by typing
>> B = A( : , [4,2,1,3] )
For example
>> B = A( : , [4, 2, 1, 3] )
B=
11 2 1 7
12 4 3 9
13 6 20 10
0 0 0 0 0 0
1 2 7 11
0 0 0 0 0 0
P A 3 4 9 12
0 0 0 0 0 0 5
0
6 10 13
0 0 0 0 0
>> P = [0,0,0,0,0,0;0,0,0,0,0,0
0,0,0,0,0,0;0,0,0,0,0,0];
>> A = [1, 2, 7, 11; 3, 4, 9, 12; 5, 6, 10, 13];
>> P(2:4,2:5) = A
P=
0 0 0 0 0 0
0 1 2 7 11 0
0 3 4 9 12 0
0 5 6 10 13 0
Assuming matrix A is
1 2 7 11
A 3 4 9 12
5 6 10 13
To delete the second row of matrix A, type
>>A([2],:)=[]
For example
21
>>clear A
To transpose a matrix and creating complex conjugates, the operator ― ‗ ‖ is used.
To transpose a matrix without creating complex conjugates, the operator ― .‗ ‖ is used.
Assuming matrix A is
1 j 2 3 j
A
3 1 4 j
The transpose operators can be applied to matrix A as follows
22
Table 16 Functions for constructing special matrices
Function Description
eye(n) Creates an n x n identity matrix.
eye(size(A)) Creates an identity matrix the same size as the matrix A.
ones(n) Creates an n x n matrix of 1s.
ones(m,n) Creates an m x n array of 1s
ones(size(A)) Creates an array of 1s the same size as the array A.
(i) Element-by-element operation: This includes array addition, array subtraction, element by element
multiplication, etc. as summarised in Table 16.
Table 16 Element-by-element array operation
Symbol Operation Form Example
+ Scalar-array addition A+b [2, 5] + 4 = [6, 9]
- Scalar-array subtraction A-b [10, 7] - 6 = [4, 1]
+ Array addition A+B [2, 5] + [10, 7] = [12, 12]
- Array subtraction A-B [2, 5] + [10, 7] = [-8, -2]
.* Array multiplication A .* B [2, 5] .* [10, 7] = [20, 35]
./ Array right division A ./ B [2, 5] ./ [10, 7] = [2/10, 5/7]
.\ Array left division A .\ B [2, 5] .\ [10, 7] = [2\10, 5\7]
.^ Array exponentiation A .^ B [2, 5] .^ 3 = [2 ^ 3, 5^3]
Array addition and subtraction require that both arrays be the same size. The only exception to this rule in
MATLAB occurs when we add or subtract a scalar to or from an array. When two arrays have identical sizes,
their sum or difference has the same size and is obtained by adding or subtracting their corresponding elements;
e.g., if
1 2 5 9
A and B
3 4 10 13
Then
1 2 5 9 6 11
A B
3 4 10 13 13 17
For example
>>A = [1,2;3,4];
>>B = [5,9;10,13];
>>A + B
ans =
6 11
13 17
23
MATLAB defines element-by-element multiplication only for arrays that are of the same sizes.
For example
>>A = [1,2;3,4];
>>B = [5,9;10,13];
>>A .* B
ans =
5 18
30 52
Example 1
The voltage, v, across a resistor is given as (Ohm‘s Law), v = Ri , where i is the current and R the resistance. The
power dissipated in resistor R is given by the expression
P = Ri2
If R = 10 Ohms and the current is increased from 0 to 10 A with increments of 2 A, write a MATLAB program
to generate a table of current, voltage and power dissipation.
Solution
% Voltage and power calculation
R=10; % Resistor value
i = (0:2:10); % Generate current values from 0 A to 10 A in steps of 2 A
v = i .* R; % array multiplication to obtain voltage
P = (i .^ 2)*R; % power calculation
fprintf('Current:\t')
fprintf('%d \t', i) % display current values
fprintf('\n')
fprintf('Voltage:\t')
fprintf('%d \t', v) % display voltage values
fprintf('\n')
fprintf('Power:\t')
fprintf('%d \t', P) % display power values
fprintf('\n')
24
1 2 1 x 5 2 x 7 1 x 9 2 x 6 19 21
5 9
AB 3 4 = 3 x 5 4 x 7 3 x 9 4 x 6 43 51
3 9 7 6 3 x 5 9 x 7 3 x 9 9 x 6 78 81
To execute it in MATLAB, one may type the following:
>>A = [1,2;3,4;3,9];
>>B = [5,9;7,6];
>>A*B
ans =
19 21
43 51
78 81
Matrix division can either be the left division operator \ or the right division operator /. The right division A/B,
for instance, is algebraically equivalent to
A
B
while the left division A\B is algebraically equivalent to
B
A
If B * C = A and B is non-singular, the left division, B\A is equivalent to MATLAB expression
C = inv(B) *A
where inv is the MATLAB function for obtaining the inverse of a matrix. The right division denoted by A/B is
equivalent to the MATLAB expression
C = A *inv(B)
Matrix exponentiation:
Raising a matrix to a power is equivalent to repeatedly multiplying the matrix by itself, for example, A2 = AA.
This process requires the matrix to have the same number of rows as columns; that is, it must be a square matrix.
MATLAB uses the symbol ―^‖ for matrix exponentiation. To find A2, type A^2.
If A is a 3 x 3 x 2 array, the element in row 3, column 2 of page 2 can be accessed by typing A(3,2,2). To access
all of page 1, type A( : , : , 1). To access all of page 2, type A( : , : , 2).
A multidimensional array can be created by first creating a two-dimensional array and then extending it. For
example, to create a three dimensional array whose first two pages are
1 2 5 5 9 8
3 4 0 and 10 13 6
1 6 3 2 9 4
To do so, first create page 1 as a matrix and then add page 2, as follows:
25
>>A = [1, 2, 5; 3, 4, 0;1, 6, 3];
>>A(: , :, 2) = [5, 9, 8; 10, 13, 6; 2, 9, 4];
The IF Statement
The if statement‘s basic form is
if logical expression
statements
end
Every if statement must have an accompanying end statement. The end statement marks the end of the statements
that are to be executed if the logical expression is true. A space is required between the if and the logical
expression, which may be a scalar, a vector, or a matrix.
For example
if x >= 0
y = sqrt(x)
end
For example
if x >= 0
y = sqrt(x)
else
y = exp(x) - 1
end
When the test, if logical expression, is performed, where the logical expression may be an array, the test returns
a value of true only if all the elements of the logical expression are true! For example, if we fail to recognize
how the test works, the following statements do not perform the way we might expect.
x = [4, -9, 25];
if x < 0
disp('Some of the elements of x are negative. ')
else
y = sqrt(x)
end
26
y=
2 0 + 3.000i 5
The else and elseif statements may be omitted if not required. However, if both are used, the else statement must
come after the elseif statement to take care of all conditions that might be unaccounted for.
For example
if x >= 5
y = log(x)
elseif x >= 0
y = sqrt(x)
end
Note that the elseif statement does not require a separate end statement.
Example 2
A 3-bit analog to digital converter, with an analog input x and digital output y, is represented by the equation:
y=0 x< -2.5
=1 -2.5 ≤ x < -1.5
=2 -1.5 ≤ x < -0.5
=3 -0.5 ≤ x < 0.5
=4 0.5 ≤ x < 1.5
=5 1.5 ≤ x < 2.5
=6 2.5 ≤ x < 3.5
=7 x≥ 3.5
(a) Write a MATLAB function to convert analog signal x to digital signal y.
(b) Test the program by obtaining the corresponding digital outputs y1, y2 and y3 for analog signal inputs x1,
x2, and x3 when the amplitudes of the inputs are
(i) x1 = -1.25
(ii) x2 = 2.57
(iii) x3 = 6.0
(c) What are the results obtained in part b(i) through b(iii) above
Solution
(a) The following program is written and saved as an m-file with the file name ―analog_to_digital.m‖
%{
analog_to_digital is a function program for obtaining the digital value given an input analog
signal
27
Note that:
Y_dig is the digital number (in integer form)
X_analog is the analog input (in decimal form)
%}
y1 =
2
y2 =
6
y3 =
7
for Loops
A loop is a structure for repeating a task a number of times. Each repetition of the loop is called a pass.
MATLAB uses two types of explicit loops namely
-the for loop: used when the number of passes is known ahead of time, and
-the while loop: used when the looping process must terminate when a specified condition is satisfied
and thus the number of passes is not known in advance.
28
The typical structure of a for loop is
The expression m:s:n assigns an initial value of m to the loop variable, which is incremented by the value s,
called the step value or incremental value. The statements are executed once during each pass, using the current
value of the loop variable. The looping continues until the loop variable exceeds the terminating value n.
For example
for k = 5:10:35
x = k^2
end
The loop variable k is initially assigned the value 5, and x is calculated from x = k^2. Each successive pass
through the loop increments k by 10 and calculates x until k exceeds 35. Thus k takes on the values 5, 15, 25,
and 35; and x takes on the values 25, 225, 625, and 1225.
Example 3
Write a MATLAB program for constructing a 5x5 matrix that has 1s in the first row and first column, and whose
remaining elements are the sum of two elements, the element above and the element to the left, if the sum is less
than 20. Otherwise, the element is the maximum of those two element values. The following function creates this
matrix. The row index is r; the column index is c.
Solution
A = ones(5);
for r = 1:5
for c = 1:5
if (r > 1) & (c > 1)
s = A(r-1,c) + A(r,c-1);
if s < 20
A(r,c) = s;
else
A(r,c) = max(A(r-1,c),A(r,c-1));
end
end
end
end
disp(A)
1 1 1 1 1
1 2 3 4 5
1 3 6 10 15
1 4 10 10 15
1 5 15 15 15
29
Example 4
Consider the array A given as
2 10 4
A 16 20 49
81 64 8
Write a MATLAB program that constructs an array B such that each element in B is obtained by computing the
square root of a corresponding element in A if the element in A is not less than 0. If an element in A is less than
0, the corresponding element in B is obtained by adding 50 to the element in A.
Solution
A = [-2, -10, 4; 16, -20, 49; 81, 64, -8];
for m = 1:size(A,1)
for n = 1:size(A,2)
if A(m,n) >= 0
B(m,n) = sqrt(A(m,n));
else
B(m,n) = A(m,n) + 50;
end
end
end
disp(B)
B=
48 40 2
4 30 7
9 8 42
WHILE LOOP
A WHILE loop allows the execution of a group of statements to be repeated as long as a specified condition is
satisfied. The general form of the WHILE loop is
while expression 1
statement group 1
end
When expression 1 is true, statement group 1 is executed. At the end of executing the statement group 1, the
expression 1 is retested. If expression 1 is still true, the statement group 1 is again executed. This retesting and
statement execution continues until expression 1 is false, then program exits the while loop. The following
example illustrates the use of the while loop.
For example
x = 5;
while x < 25
disp(x)
30
x = 2*x - 1;
end
The results displayed by the disp statement are 5, 9, and 17. The loop variable x is initially assigned the value 5,
and it has this value until the statement x = 2*x - 1 is encountered the first time. The value then changes to 9.
Before each pass through the loop, x is checked to see whether its value is less than 25. If so, the pass is made. If
not, the loop is skipped and the program continues to execute any statements following the end statement.
For the while loop to function properly, the following two conditions must be satisfied:
1. The loop variable must have a value before the while statement is executed.
2. The loop variable must be changed somehow by the statements enclosed in the while loop.
Example 5
Write a script to determine the number of terms required for the sum of the series
5k2 - 2k, k = 1, 2, 3, . . . , to exceed 10 000. What is the sum for this many terms?
Solution
Because number of times that the expression 5k2 - 2k is to be evaluated is unknown, a while loop can be
employed. The script file is as follows:
total = 0;
k = 0;
while total < 1e+4
k = k + 1;
total = 5*k^2 - 2*k + total;
end
disp('The number of terms is: ')
disp(k)
disp('The sum is: ')
disp(total)
31
otherwise
statement group n
end
The input expression is compared to each case value. If they are the same, then the statements following that
case statement are executed and processing continues with any statements after the end statement.
If the input expression is a string, then it is equal to the case value if strcmp returns a value of 1 (true). Only the
first matching case is executed.
If no match occurs, the statements following the otherwise statement are executed. However, the otherwise
statement is optional. If it is absent, execution continues with the statements following the end statement if no
match exists. Each case value statement must be on a single line.
For example, suppose the variable angle has an integer value that represents an angle measured in degrees from
North. The following switch block displays the point on the compass that corresponds to that angle.
switch angle
case 45
disp('Northeast')
case 135
disp('Southeast')
case 225
disp('Southwest')
case 315
disp('Northwest')
otherwise
disp('Direction Unknown')
end
The switch statement can handle multiple conditions in a single case statement by enclosing the case value in a
cell array. For example, the following switch block displays the corresponding point on the compass, given the
integer angle measured from North.
switch angle
case {0,360}
disp('North')
case {-180,180}
disp('South')
case {-270,90}
disp('East')
case {-90,270}
disp('West')
otherwise
disp('Direction Unknown')
end
32
Example 6
Table 18 shows the grouping of the months of the year based on the number of days they have. Based on the
information in Table 18, write a MATLAB script that displays the number of days in a month when the answers
to the following two questions are supplied by the user of the script:
1. Enter the month
2. Is it a leap year (y/n)
Table 18 Grouping of the months of the year based on the number of days
they have
Months classified by number of days Number of days in a month
February (Common year) 28
February (Leap year) 29
September, April, June, November 30
January, March, May, July, August, October, 31
November, December
Solution
msg = 'Enter the month: ';
month = input(msg, 's');
month_3_letters = month(1:3); % Just use the first three letters
if lower(month_3_letters) == 'feb'
leap = input( 'Is it a leap year (y/n): ', 's');
end
switch lower(month_3_letters)
case { 'sep', 'apr', 'jun', 'nov'}
days = 30;
case 'feb'
switch lower(leap)
case 'y'
days = 29;
otherwise
days = 28;
end
otherwise
days = 31;
end
fprintf('%s has %d days ', month, days)
33
y = sqrt(x);
end
However, it is usually possible to write the code to avoid using the break command. This can often be done with
a while loop as explained previously. The break statement stops the execution of the loop.
There can be applications where we want to not execute the case producing an error but continue executing the
loop for the remaining passes. We can use the continue statement to do this. The continue statement passes
control to the next iteration of the for or while loop in which it appears, skipping any remaining statements in the
body of the loop. In nested loops, continue passes control to the next iteration of the for or while loop enclosing
it.
For example, the following code uses a continue statement to avoid computing the logarithm of a negative
number.
x = [10,1000,-10,100];
y = NaN*x;
for k = 1:length(x)
if x(k) < 0
continue
end
kvalue(k) = k;
y(k) = log10(x(k));
end
kvalue
y
kvalue =
1 2 0 4
y=
1 3 NaN 2
is equivalent to
A = [1,2,3;4,5,6];
n = 3;
for k = 1:n
v = A(:, k)
end
34
Tutorial Questions
Question 1
Consider the matrix
2 10 50
3 13 7
A
6 0 8
1 4 10
Using relational operators, write a MATLAB script that sets all the terms of this matrix which are greater than 2
and less than 15 equal to 0.
Solution
(Approach 1)
A =[2,10,50;-3,13,7;-6,0,8;1,4,10];
B = 2*ones(4,3);
C = 15*ones(4,3);
% Make the comparisons
D = B < A; % 1, if the term in A > 2
E = C > A; % 1, if the term in A < 15
% Positions of the numbers which lie between 2 and 15
F = D & E; %The matrix F contains a 1 if the terms of A lie within the given limits; otherwise a 0.
result = F.*A
(Approach 2)
A =[2,10,50;-3,13,7;-6,0,8;1,4,10];
for i = 1:4
for j = 1:3
if (A(i,j) <= 2 || A(i,j) >= 15)
A(i,j) = 0;
end
end
end
disp(A)
Question 2
Write a MATLAB script for computing the values of the signal (function)
s(t) = sin (2π5t) cos (2π3t) + e-0.1t
for a time vector between 0 and 10 with a step size of 0.1.
Solution
% Define time vector
t = 0:0.1:10;
% Define signal value
s = sin(2*pi*5*t).*cos(2*pi*3*t) + exp(-0.1*t)
plot(t,s)
Question 3
A 3-bit analog to digital converter, with an analog input x and digital output y, is represented by the equation:
y=0 x< -2.5
=1 -2.5 ≤ x < -1.5
66
=2 -1.5 ≤ x < -0.5
=3 -0.5 ≤ x < 0.5
=4 0.5 ≤ x < 1.5
=5 1.5 ≤ x < 2.5
=6 2.5 ≤ x < 3.5
=7 x≥ 3.5
Based on the MATLAB SWITH…CASE construct, write a function that converts analog signal x to digital
signal y.
Solution
The required program is as follows and it is written and saved with the file name ―analog_to_digital.m‖:
%{
analog_to_digital is a function program for obtaining the digital value given an input analog
signal
Note that:
Y_dig is the digital number (in integer form)
X_analog is the analog input (in decimal form)
%}
Question 4
Write a MATLAB script that plots the exponential functions e−t/2 and e−2t/5 against variable t (assuming t spans
the interval [0, 2])
(a) in a single overlay plot,
(b) beside each other in different plots, and
(c) one above the other in different plots.
67
Solution
t = 0:0.01:2;
f1 = exp(-t/2);
f2 = exp(-2*t/5);
figure
%Question (a): A single overlay plot,
plot(t,f1,'b',t,f2,'r');
figure
%Question (b): beside each other in different plots
subplot(1,2,1); % Plot the first function
plot(t,f1,'b');
subplot(1,2,2); % Plot the second function next to it
plot(t,f2,'r');
figure
%Question (c): one above the other in different plots.
subplot(2,1,1); % Plot the first function
plot(t,f1,'b');
subplot(2,1,2); % Plot the second function below the first
plot(t,f2,'r');
Question 5
Sketch the result(s) obtained if the MATLAB script in Fig. Q5 is executed
A = [0, 1, 2, 3; 0, 1, 2, 3];
B = [0,1,2,3];
C = [0,1];
subplot(2,1,1)
plot(B,A)
xlabel('x-axis')
ylabel('y-axis')
subplot(2,1,2)
plot(C,A)
xlabel('x-axis')
ylabel('y-axis')
Fig. Q5
Solution
3
2 The length of vector B is equal to the number of columns in
y-axis
0 1 2 3
x-axis
68
y-axis 3
2 The length of vector C is equal to the number of rows in matrix
1 A; therefore, the columns in matrix A are plotted against vector C
0 1
x-axis
Question 6
Consider the MATLAB command in Fig. Q6 which contains the academic record of a student.
Solution
(a) Student‘s name is in cell(1,1) . The following command can be used to change the student‘s name:
Student{1,1} = 'Ade Omofatajeun '
(b) The courses registered for are in cell(2,1). The following commands can be used to display the courses:
Student{2,1}{1}, Student{2,1}{2}
(c) The last number is in cell(2,2). The following command can be used to add 20 to it:
Student{2,2}([4]) = Student{2,2}([4]) + 20
Question 7
Write a MATLAB script for computing the base 2 and base 10 logarithms of the vector
b = (1024 1000 100 2 1)
Solution
% Define the vector b
b = [1024 1000 100 2 1];
log10ofb = log10(b) % Calculate the base 10 logarithm
log2ofb = log2(b) % Calculate the base 2 logarithm
Question 8
Write a MATLAB script for plotting the quadratic expression x2+7x−3 from x equals -3 to +3 in steps of 0.2.
Solution
x = -3:0.2:3;
y = x.ˆ2+7.*x-3;
grid on
plot(x,y)
69
Question 9
Write a MATLAB script for computing the sum of the following geometric progression:
10
2
n 1
n
Solution
total = 0
for n = 1:6
total = total + 2ˆn;
end
Question 10
Consider the inverting amplifier circuit shown in Fig. Q10. If the relationship between the output voltage Vo and
the input voltage Vg is
R 10 1 1
Vo 2 Vg where Vg 2 cos 3 t cos 9 t cos 15 t
R1 , π 9 25
Write a MATLAB script that
(i) computes the values of voltage Vo, assuming time t ranges from 0 to 3 in steps of 0.05.
(ii) plots the values of output voltage Vo computed in part (i) and input voltage Vi against time t.
(Hint: Assume that Vo is clipped at ±2, which is a constraint imposed by the power supply rails.)
Solution
%Question (i)
t = 0:0.05:3 R2 = 10K
r1 = 2e3;
r2 = 10e3; R1 = 2K +2V
y1 = 10/(pi^2); +
y2 = cos(3*pi.*t); Vg
1.5
0.5
-0.5
-1
_
y3 = 1/9*cos(9*pi.*t);
-1.5
-1 0 1 2 3 4 5 6 7
-2V Vo
y4 = 1/25*cos(15*pi.*t);
vg = y1.*(y2+y3+y4); Fig. Q10
vo = (-r2/r1).*vg;
for i = 1:length(vo)
if vo(i)>2
2.5
vo(i)=2; Vg
2 Vo
elseif vo(i)<-2
1.5
vo(i)=-2; 1
end 0.5
Voltage (V)
end 0
[t ; vo]' -0.5
-1
70
legend('Vg','Vo')
xlabel('Time (s)')
ylabel('Voltage (V)')
Question 11
Write a MATLAB script that rounds off the values of the vector
s(t) = 20 sin (2π5.3t)
once up and once towards zero. Assume time vector ranges between 0 and 10 with a step size of 0.1.
Solution
% Define the time vector
t = 0:0.1:10;
% Define signal values
s = 20*sin(2*pi*5.3.*t);
% Round s toward infinity (up) using the function ceil
s2infinity = ceil(s)
% Round s toward 0 with the function fix
s2zero = fix(s)
Question 12
Determine the result of the following MATLAB command
char(2*34-3)
Solution
2*34-3 = 65
Referring to Table 11 which contains the ASCII characters and their decimal values, it can be observed
that decimal 65 equals ASCII character ―A‖
Therefore,
char(2*34-3) = char(65) = A
Question 13
Refer to Fig. Q13 and provide the MATLAB command for executing the following:
A =[2,10,50;-3,13,7;-6,0,8;1,4,10];
B = [1,2,3;4,5,6;7,8,9,10,11,12];
C = [1,3,5;5,3,1;7,5,3];
Fig. Q13
(i) Replace the third row in matrix B with the row vector [12 14 15]
(ii) Raise matrix C to the power of 4
(iii) Raise each element in matrix C to the power of 4
(iv) Add each element in matrix A to a corresponding element in Matrix B
(v) Sum the elements in each column of the matrix A and return a row vector containing the sums.
(vi) Interchange the first and last columns of matrix B
(vii) Interchange the second and third rows of matrix A
Solution
(i) B(3,:) = [12 14 15]
(ii) C ^ 4
(iii) C .^ 4
(iv) A .+ B
(v) sum(A)
71
(vi) B(:,[3 2 1])
(vii) A([1 3 2 4]; :)
Question 14
For the electric circuit shown in Fig. Q14, compute the impedance Zab and write a MATLAB script to
(i) Plot the real part of the impedance Zab versus frequency ω.
(ii) Plot the imaginary part of the impedance Zab versus frequency ω.
(iii) Plot the impedance Zab versus frequency ω in polar coordinates. a
10 Ω
Solution
10 Ω
Zab C = 10 μF
10 j 0.1 1
j10 10
6 0.1 H
Z ab 10
1
10 j 0.1
j10 10 6 b
Fig. Q14
10 j 0.1 j105 1
= 10
1
10 j 0.1 j10 5
j10 6
10 4
= 10
10 5
10 j 0.1
%Question (i)
figure
real_part = real(z);
plot(w,real_part)
grid
xlabel('radian frequency w');
ylabel('Real part of Z');
%Question (ii)
figure
imag_part = imag(z);
plot(w,imag_part);
grid;
xlabel('radian frequency w');
ylabel('Imaginary part of Z');
72
%Question (iii)
figure
mag = abs(z); % Computes |Z|
theta = angle(z); % Computes the phase angle of impedance Z
polar(theta,mag); % Polar plot
grid;
ylabel('Polar Plot of Z');
Question 15
Refer to the RLC circuit in Fig. Q15 and
Vo
(i) determine the transfer function H
Vi
(ii) write a MATLAB script to compute the poles and zeros of the transfer function H(ω).
(iii) write a MATLAB script to plot the frequency response of the circuit.
R1 = 100 Ω (4 marks)
R2 =
300 Ω
+1.5
L1 = 2 H Vo(t)
Vi(t)
1
0.5
-0.5
-1
-1.5
-1 0 1 2 3 4 5 6 7
- C1 = 0.5 F
Fig. Q15
Question (i)
Apply voltage divider rule to obtain Vo(s):
1
300 2s
VO s 0.5s
Vi s
1
300 2s 100
0.5s
VO s 0.5s300 2s 1 s 150s 1
2
Vi s 0.5s400 2s 1 s 2 200s 1
Hence, the transfer function is
2
s 150s 1
H s 2
,
s 200s 1
Question (ii)
-The zeros are computed by finding the roots of the numerator of the transfer function
73
The numerator = s2 + 150s + 1
This polynomial is written as row vector [1 150 1] in MATLAB parlance
-The poles are computed by finding the roots of the denominator of the transfer function
The numerator = s2 + 200s + 1
This polynomial is written as row vector [1 200 1] in MATLAB parlance
The following program computes the poles and zeroes of the transfer function
%Question (iii)
% Frequency response
num = [1 150 1]; % numerator polynomial Alternatively:
den = [1 200 1]; % denominator polynomial numerator = (s).^2+(150.*s) +1 ;
w = 0:1000; denominator = (s).^2+(200.*s) +1;
s = j.*w;
Hs = numerator./denominator;
Hs_abs = abs(Hs); % Compute the magnitude of the transfer function
subplot(1,2,1)
semilogx (w,Hs_abs)
xlabel('Radian Frequency w rad/s − log scale'); ylabel(' |G(w)| ')
grid
Hs_ang = angle(Hs)/pi *180; % Compute the phase of the transfer function (in degrees)
subplot(1,2,2)
semilogx(w,Hs_ang)
xlabel('Radian Frequency w rad/s − log scale'); ylabel(' phase (deg) ')
grid
74