0% found this document useful (0 votes)
6 views

ELE 562 NOTE (Part 1 and Tutorial Questions) - 2

Note On Electrical Maitainability

Uploaded by

aiyepeks
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

ELE 562 NOTE (Part 1 and Tutorial Questions) - 2

Note On Electrical Maitainability

Uploaded by

aiyepeks
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 43

ELE 562 – USE OF ENGINEERING SOFTWARE PACKAGES

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.

Advantages of using MATLAB


1. MATLAB has an excellent documentation
2. Many toolkits are available which extend MATLAB‘s functionality
3. MATLAB is equipped with an editor with debugging functionality, which makes the writing and error
analysis of large programs very easy.
4. MATLAB‘s matrix manipulation algorithms (esp. for sparse matrices) are state of the art
5. MATLAB interacts with a special toolbox, Simulink, which is a tool for constructing simulation programs
based on a graphical interface in a way similar to block diagrams.

Disadvantages of using MATLAB


1. The scripting system of MATLAB is somewhat primitive
2. For complex tasks (especially ones which require for loops), MATLAB can sometimes be slower than C or
C++
3. MATLAB is a commercial software; meaning that it is not free (it is expensive!)

MATLAB User Interface

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

Fig. 1 The default MATLAB desktop

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.

Ways of using MATLAB


There are 2 ways in which MATLAB can be used, which are: command
(1) Using the command window and
(2) Using an m-file
result
(1) Using the command window:
MATLAB commands or statements can be entered into the command
command window. Once the statement has been entered, the prompt
<return> key is pressed in order to execute the command. For
example, the addition of numbers 1, 3, and 8 can be executed
in the command window as shown in Fig 2. MATLAB displays
the prompt (>>) to indicate that it is ready to receive Fig. 2 A statement issued in the command
instructions. window for performing an addition task

(2) Using an m-file:


For complicated problems, the simple editing tools provided by the Command Window is insufficient. A
much better approach is to create an m-file. An m-file contains lines of code entered into any text editor and
saved with the ―.m‖ file extension. There are 3 types of m-files namely; (i) Script m-file, (ii) Function m-file
and (iii) Class m-file.
(i) Script m-file:
An m-file is by default a script m-file. A script m-file literally contains a list of MATLAB commands
without any argument. Suppose ―addition.m‖ is a script m-file saved in the current directory (that is,

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

Command for invoking


the script-m file

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

(ii) Function m-file:


A function m-file is a file in which a function is defined. The first (non-comment) line of a function m-
file takes the form:
function [output args] = function_name(input args)
It should be noted that the name of the function needs to be the same as the filename of the m-file
For example, if addition.m is a function m-file and it is saved in the current folder, this function can be
invoked by typing the following command in the command window (see Fig 4.2):
>>d = addition(1,3,8)

Editor window Command for invoking


Output argument Input argument Command window the function-m file

Result

Fig. 4.1 A function m-file which has been saved with


the file name ―addition.m‖ which contains the Fig. 4.2 Invoking the code in the saved function m-file.
formula for adding any 3 numbers passed as Note that the file name of the function m-file in
argument to it this case is ―addition.m‖

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.

(iii) Class m-file:


This file type is usually used for implementing object-oriented programming in MATLAB. Similar
to function m-file, the file name must agree with the class name. The functions defined for objects of
a class are called class methods. Assuming function ―add‖ is a method in class ―addition‖ and an
object ―numbers‖ is created from class ―addition‖, it is possible to call the method ―add‖ by typing
either numbers(add) or numbers.add. See Figs. 5.1 and 5.2.

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.2 Invoking the code in the saved class


m-file. Note that the file name of the
class m-file in this case is
―addition.m‖

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.

Rules for naming variables in MATLAB


A variable in MATLAB is a symbol used to hold a value. The rules for naming variables in MATLAB can be
summarised as follows:
1. Variable names in MATLAB can be up to 31 characters long
2. Variable names in MATLAB must start with a letter. The subsequent characters can be numbers, letters or
underscores (some other characters are also available). There are many choices which are forbidden as
variable names, some for very obvious reasons (such as a*b which signifies a multiplication of the variables a
and b) and others for more subtle reasons.
3. Variable names in MATLAB are case sensitive, so that voltage and VOLTAGE are two different objects.

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.

Table 1 Scalar arithmetic operators


Operation Operator symbol MATLAB
form
Exponentiation: ab ^ a^b
Multiplication: ab * a*b
a
Right division: a/b = / a/b
b
b
Left division: a\b= \ a\b
a
Addition: a+b + a+b
Subtraction: a-b - a-b

Order of arithmetic operator precedence


Mathematical expressions are evaluated starting from the left, with the exponentiation operation having the
highest order of precedence, followed by multiplication and division with equal precedence, followed by
addition and subtraction with equal precedence as illustrated in Table 2.

Table 2 Order of precedence


Precedence Operation
First Parentheses, evaluated starting with the innermost pair
Second Exponentiation, evaluated from left to right
Third Multiplication and division with equal precedence, evaluated
from left to right
Fourth Addition and subtraction with equal precedence, evaluated from
left to right

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

Complex Number Operations


MATLAB handles complex number algebra automatically. For example, the number c1 =1 - 2i is entered as
follows:

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,

>>s = 3+7i; w = 5-9i;


>>w+s
ans =
8.0000 - 2.0000i

>>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
%}

Controlling Input and Output


MATLAB provides several useful commands for obtaining input from the user and for formatting the output (the
results obtained by executing the MATLAB commands). Table 6 summarizes these commands.

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.

Table 6 Input/output commands


Command Description
disp(A) Displays the contents, but not the name, of the array A.
disp(„text‟) Displays the text string enclosed within single quotes.
format Controls the screen‘s output display format (see Table 7).
x = input(„text‟) Displays the text in quotes, waits for user input from the keyboard, and stores the
value in x.
x = input(„text‟, „s‟) Displays the text in quotes, waits for user input from the keyboard, and stores the
input as a string in x.
k=menu(„title‟, „option 1‟, Displays a menu whose title is in the string variable ‗title‘ and whose choices are
„option 2‟, ..., „option n‟) ‗option1‟, ‗option2‟, and so on.

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

Table 7 Formatting command


Command Description
format short Four decimal digits (the default); e.g., 13.6745.
format long 16 digits; e.g., 17.27484029463547.
format short e Five digits (four decimals) plus exponent; e.g., 6.3792e+03.
format long e 16 digits (15 decimals) plus exponent; e.g., 6.379243784781294e-04.
format bank Two decimal digits; e.g., 126.73.

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.‖

\n, which means "go to a new line"

Table 8 contains additional format specifiers and their meanings

Table 8 Format specifiers and their meanings


Format specifier Description
c single character
d decimal notation (but no decimal if integral)
e exponential notation
E exponential notation with an upper case E
F fixed-point notation
g shorter of e or f
G shorter of e or f but with an upper case
o unsigned octal notation
s string
u unsigned decimal notation
x hexadecimal notation
X hexadecimal notation with uppercase

MATLAB built-in mathematical functions


MATLAB has many built-in functions, including trigonometric, logarithmic, and hyperbolic functions, as well as
functions for processing arrays. Some common mathematical functions are summarised in Table 9.

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

MATLAB data types are classified as


(i) Numeric Data Type
(ii) String Data Type
(iii) Cell Data Type
(iv) Struct Data Type

(I) Numeric Data Type


The default data type used by MATLAB to store a number is ―double” which is so versatile that it is capable of
handling almost any numerical problem that comes up in engineering and science applications. A comprehensive
list of MATLAB numeric data type is shown in Table 10.
Table 10 Numeric data types and their range of values
Data Type Range of Values
int8 -27 to 27-1
int16 -215 to 215-1
int32 -231 to 231-1
int64 -263 to 263-1
uint8 0 to 28-1
uint16 0 to 216-1
uint32 0 to 232-1
uint64 0 to 264-1
single -3.4x1038 to 3.4x1038, Inf, NaN
double -1.79x10308 to 1.79x10308, Inf, NaN

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

(II) String Data Type


A string is a row vector of numbers of type char, each number being a code that represents one character.
A string is defined with the use of the ‗ ‘ operator.
The general syntax is:
the_string = ‘somecharacters‘
For example
>> t = ‗a string‘
t=
a string

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

>> course = ‗ELE 562‘;


>>double(course) Table 12 Some string functions
ans =
Function Description
69 76 69 32 53 54 50
char converts type to char
Numbers can also be converted to characters. findstr finds the positions of a substring in a string
For example ischar returns 1 if argument is a character array and 0
otherwise
isletter finds letters in string
>> course = ‗ELE 562‘;
isspace finds spaces, newlines, and tabs in string
>>New_course = course + 1
ans = isstrprop finds characters of specified type in string
70 77 70 33 54 55 51 num2str converts number to string
>>char(New_course) length determines the number of letters in string
ans = lower converts string to lower case
FMF!673 sprintf writes formatted data to string
strcmp compares strings
strcmpi like strcmp but independent of case
strmatch search array for rows that begin with specified
Some string functions are illustrated in Table 12 string
strncmp like strcmp but compares only first n characters
strncmpi like strncmp but independent of case
str2num converts string to number
upper converts string to upper case

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
 

The cell may be constructed using the MATLAB statement:


Student = {„ADE‟, „13/30GC1000‟; {„ELE447‟;‟ELE562‟}, [25,45; 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.

Accessing cell data


To display cell array Student, the celldisp function can be used. To access a specific cell of a cell array the curly
brackets are used. For example

>>Student = {‗ADE‘, ‗13/30GC1000‘; {‗ELE447‘;‘ELE562‘}, [25,45; 22,50]};


>> celldisp(Student)
Student{1,1} =
ADE
Student{2,1}{1} =
ELE447
Student{2,1}{2} =
ELE562
Student{1,2} =
13/30GC1000
Student{2,2}
25 45
22 50

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

Assigning data to cells


Data can be assigned to the cells by using either
(i) cell indexing or
(ii) content indexing

(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
 

The cells can be assigned data values as follows:

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]

Some cell functions are illustrated in Table 13


Table 13 Some cell functions and their description
Function Description
cell create an array of type cell
celldisp show all the objects pointed at by a cell array
cellfun apply a function to all the objects pointed at by a cell array
cellplot show a graphical depiction of the contents of a cell array
cell2struct convert a cell array into a struct array
deal copy a value into output arguments
iscell returns true if argument is of type cell
num2cell convert a numeric array into a cell array

(IV) Struct data type


An array in most programming languages, consists of a collection of elements, each of which has the same
elementary data type. The array is said to be homogeneous with regard to the types of its element. It is not
possible, therefore, to have a matrix whose first element is of type int16 and whose second element is of type
char. A struct provides a way of having multiple data types within a single variable.
A struct differs from an array in the following respects
(i) The elements of an array always have the same data type but a struct can have elements belonging to different
data types.
(ii) Each element of an array has a numerical index but the index of an element of a struct is usually a user-
defined name.

Structs use the dot notation (.) to specify and to access the fields.

A struct can be created in two ways


(i) By using assignment statements
(ii) By using struct functions

Using assignment statement


Supposing it is desired to create a struct that contains the following types of student data:
*Student name
*Student matric number
*Student email
*Student age
This can be accomplished as follows

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;

The data of the second student can be viewed as follows:

>>student(2)
name: ‗CHIKE‘
matric_no : ‗13/30GC1001‘
email : ‗[email protected]
age: 23

Using struct function


As an alternative to assignment statement, stucts can be constructed using the struct function which preallocates
a struct array. To build a struct array named str_array, the syntax is:
str_array = struct(‗ field1‘,‘values1‘, ‗field2‘, ‗values2‘, ‗field3‘, ‗values3‘, . . .)

For example

>>student = struct(‗name‘,‗ADE‘, ‗matric_no‘ , ‗13/30GC1000‘,…


‗email‘, ‗[email protected]‘, ‗age‘, 21)

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

Table 14 Some struct functions


Function Description
names = fieldnames(student) Returns the field names associated with the struct array student
isfield(student, ‗this_field‘) Returns 1 if ‗this_field‘ is the name of a field in the struct array
student and 0 otherwise.
isstruct(student) Returns 1 if the array student is a struct array and 0 otherwise.
student = rmfield(student, ‗this_field‘) Removes the field ‗this_field‘ from the struct array student
student = struct(‗ field1‘,‘values1‘, ... Creates a struct array student with the fields ‗field1‘, ‗field2‘, . . .
‗field2‘, ‗value2‘, ‗field3‘, ‗value3‘, . . .) having the values ‗value1‘, ‗value2‘, ...

Dimension of MATLAB Variables


By default, all variables in MATLAB are treated as matrices (i.e., array of elements). Based on dimension,
MATLAB variables can take any of the following forms:
(I) Scalar (i.e., 1 x 1 matrix)
(II) Vector (i.e., n x 1 or 1 x n matrix)
(III) Matrix (n x m matrix; where n and m may or may not be equal)
(IV) Multi-dimensional array (e.g., n x m x q array)

(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.

Assuming a matrix A is given as follows

1 2 7 11 >>A = [1, 2, 7, 11; 3, 4, 9, 12; 5, 6, 10, 13]


 
A  3 4 9 12  which is written in MATLAB as: A= 1 2 7 11
5 10 13  3 4 9 12
 6
5 6 10 13
To get the element at row 3, column 2, one may type
>>a = A(3,2)
a =
6

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

Consider the following matrices

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 

It is possible to assign new values to entire block in matrix P as follows


>> P(2:4,2:5) = A

>> 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

>>A = [1, 2, 7, 11; 3, 4, 9, 12; 5, 6, 10, 13]


>> A([2], :) = []
A=
1 2 7 11
5 6 10 13

Similarly, to delete the third column of matrix A, type


>>A(:,[3]) = []

To delete variable A from memory, one may type

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

>>A=[1-j,2+3j; 3,1+4j]; >>A=[1-j,2+3j; 3,1+4j];


A‘ A .‘
ans = ans =
1.0000 + 1.0000i 3.0000 1.0000 - 1.0000i 3.0000
2.0000 - 3.0000i 1.0000 - 4.0000i 2.0000 + 3.0000i 1.0000 + 4.0000i

Some array functions and their descriptions are illustrated in Table 15

Table 15 Array functions and their description


Function Description
find(x) Computes an array containing the indices of the nonzero elements of the array x.
length(A) Computes either the number of elements of A if A is a vector or the largest value of m or n if
A is an m x n matrix.
linspace(a,b,n) Creates a row vector of n regularly spaced values between a and b.
logspace(a,b,n) Creates a row vector of n logarithmically spaced values between a and b.
max(A) Returns the algebraically largest element in A if A is a vector. Returns a row vector
ontaining the largest elements in each column if A is a matrix. If any of the elements are
complex, max(A) returns the elements that have the largest magnitude
[x,k] = max(A) Similar to max(A) but stores the maximum values in the row vector x and their indices in the
row vector k.
min(A) Same as max(A) but returns minimum values.
[x,k] = min(A) Same as [x,k] = max(A) but returns minimum values.
norm(A) Computes a vector‘s geometric length x12  x22    xn2
size(A) Returns a row vector [m n] containing the sizes of the m x n array A.
sort(A) Sorts each column of the array A in ascending order and returns an array the same size as A.
mean(A) Mean of elements of vector A
sum(A) Sums the elements in each column of the array A and returns a row vector containing the
sums.
std(A) Standard deviation of elements of vector A

Constructing special matrices


Some MATLAB commands can be used to construct special matrices. Some of these commands are illustrated in
Table 16

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.

zeros(n) Creates an n x n matrix of 0s


zeros(m,n) Creates an m x n array of 0s.
zeros(size(A)) Creates an array of 0s the same size as the array A.

Array Arithmetic Operation


MA TLAB has two forms of arithmetic operations for arrays namely:
(i) Element-by-element operation
(ii) Matrix operation

(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')

(ii) Matrix Operations

Matrix addition and subtraction:


Matrix addition and subtraction are identical to element-by-element addition and subtraction. The corresponding
matrix elements are summed or subtracted.

Matrix multiplication and division:


Matrix multiplication and division are not the same as element-by-element multiplication and division. To
multiply matrices A and B, the number of columns in A must equal the number of rows in B and the product AB
has the same number of rows as A and the same number of columns as B.
e.g., if
1 2 
  5 9 
A  3 4  and B   
3 9   7 6 
 

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.

(IV) Multi-dimensional array:


MATLAB supports multidimensional arrays. A three-dimensional array, for instance, has the dimension m x n x
q. A four-dimensional array has the dimension m x n x q x r, and so forth. The first two dimensions are the row
and column, as with a matrix. The higher dimensions are called pages.

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];

MATLAB language construct


MATLAB has six program-like constructs. In this course, the control flow constructs are of particular interest.
The control flow constructs can be used to control the running of a sequence of commands within a program.

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

The else Statement


When more than one action can occur as a result of a decision, we can use the else and elseif statements along
with the if statement. The basic structure for the use of the else statement is
if logical expression
statement group 1
else
statement group 2
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

When this program is run, it gives the result

26
y=
2 0 + 3.000i 5

The elseif Statement


The general form of the if statement is
if logical expression 1
statement group 1
elseif logical expression 2
statement group 2
else
statement group 3
end

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)
%}

function Y_dig = analog_to_digital (X_analog)


if X_analog < -2.5
Y_dig = 0;
elseif X_analog >= -2.5 & X_analog < -1.5
Y_dig = 1;
elseif X_analog >= -1.5 & X_analog < -0.5
Y_dig = 2;
elseif X_analog >= -0.5 & X_analog < 0.5
Y_dig = 3;
elseif X_analog >= 0.5 & X_analog < 1.5
Y_dig = 4;
elseif X_analog >= 1.5 & X_analog < 2.5
Y_dig = 5;
elseif X_analog >= 2.5 & X_analog < 3.5
Y_dig = 6;
else
Y_dig = 7;
end
Y_dig;
end
(b) The function ―analog_to_digital‖ is called using the given analog inputs x1, x2, and x3 as follows
(i) x1 = -1.25
y1 = analog_to_digital (x1)
(ii) x2 = 2.57
y2 = analog_to_digital (x2)
(iii) x3 = 6.0
y3 = analog_to_digital (x3)

(c) the results obtained are

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

for loop variable = m:s:n


statements
end

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)

The result obtained after running the program is:

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)

The result obtained after running the program is:

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)

The result obtained after running the program is:

The number of terms is:


18
The sum is:
10203

The SWITCH Statement


The switch statement provides an alternative to using the if, elseif, and else commands. Anything programmed
using switch can also be programmed using if structures. However, for some applications, programs written
based on the switch statement is more readable than programs written based on the if statement. The syntax is:

switch input expression (scalar or string)


case value1
statement group 1
case value2
statement group 2
.
.
.

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)

The BREAK and CONTINUE Statements


It is permissible to use an if statement to ―jump‖ out of the loop before the loop variable reaches its terminating
value. The break command, which terminates the loop but does not stop the entire program, can be used for this
purpose. For example,
for k = 1:10
x = 50 - k^2;
if x < 0
break
end

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

The results obtained after running the program are:

kvalue =

1 2 0 4

y=

1 3 NaN 2

Using an Array as a Loop Index


It is permissible to use a matrix expression to specify the number of passes. In this case the loop variable is a
vector that is set equal to the successive columns of the matrix expression during each pass. For example,
A = [1,2,3;4,5,6];
for v = A
disp(v)
end

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)
%}

function Y_dig = analog_to_digital (X_analog)


switch true
case X_analog < -3.2
Y_dig = 0;
case X_analog >= -2.5 && X_analog < -1.5
Y_dig = 1;
case X_analog >= -1.5 && X_analog < -0.5
Y_dig = 2;
case X_analog >= -0.5 && X_analog < 0.5
Y_dig = 3;
case X_analog >= 0.5 && X_analog < 1.5
Y_dig = 4;
case X_analog >= 1.5 && X_analog < 2.5
Y_dig = 5;
case X_analog >= 2.5 && X_analog < 3.5
Y_dig = 6;
otherwise
Y_dig = 7;
end
Y_dig
end

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

matrix A, therefore, the rows in A are plotted against vector B


1

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.

>> Student = {'Ade', '13/30GC1000'; {'ELE447'; 'ELE562'}, [25,45; 22,50]};


Fig. Q6
If the name of the student is ―ADE‖, his Matric No is 13/30GC1000, and he registered for the courses ―ELE447‖
and ―ELE562‖, identify the cell where each data is entered and write a command for
(a) Changing his name to ―Ade Omofatajeun‖
(b) Displaying the courses he registered for
(c) Add 20 to the last number shown in the command of Fig. Q6 (i.e., the number 50)

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

%Question (ii) -1.5

%this script plots vo and vi against t assuming -2

% that vo has already been computed in part (i) -2.5


0 0.5 1 1.5 2 2.5 3 3.5 4
Time (s)

plot(t,vg,'b*-- ',t,vo,'r ')


axis([0 4 -2.5 2.5])

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 
 
  

The required MATLAB program is as follows:


w = 0:2000; % Define interval with one radian interval
z = (10+(10 .^ 4 -j .* 10 .^ 6 ./ (w)) ./ (10 + j .* (0.1 .* w -10.^5./ (w))));

%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 

Multiply numerator and denominator by 0.5s and rearrange terms:

VO s  0.5s300  2s   1 s  150s  1
2

 
Vi s  0.5s400  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

% Program for poles and zeros


num = [1 150 1]; % numerator polynomial
den = [1 200 1]; % denominator polynomial

disp('the zeros are')


z = roots(num) % the zeros of the transfer function
disp('the poles are');
p = roots(den) % the poles 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;

%evaluate the transfer function at s = jw


numerator = polyval(num,s); %Evaluate transfer function numerator at s = jω
denominator = polyval(den,s); %Evaluate transfer function denominator at s = jω

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

You might also like