ELE 562 Slide
ELE 562 Slide
January, 2021
ELE 562
Course Outline
8-Feb-21
2
1
08/02/2021
MATLAB
2
08/02/2021
i. Title Bar: The title bar contains the program’s name with year and logo as well as the
window control buttons. It is situated on the top of the main MATLAB window.
ii. Menu Bar: The menu bar is underneath the title bar. It has commands for opening,
closing files, preferences, open, copy, paste etc.
iii. Desktop Toolbar: The desktop toolbar is placed underneath the menu bar. It contains
many items such as, new file, new script, open, import data, help etc.
iv. Command Window: It is the most important part of the MATLAB main desktop. It is
the window where input and output appears, the user can enter commands and obtain
results. Each new line starts with the symbol “>>” called the command prompt.
v. 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.
vi. Current Folder: On the top of the window there is box containing the location of the
current directory. File names appear on the left column, file types on the middle and
last date of modification on the right column.
vii. 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, i.e their dimensions, the number of bytes they take on
memory
8-Feb-21 and their class, that is the type of variable.
6
3
08/02/2021
Files can be name whatever as may wish (usually simpler is better though), with a
few exceptions:
MATLAB for Windows retains the file naming constraints set by DOS. The
following characters cannot be used in filenames:
"/:*<>|?
You're not allowed to use the name of a reserved word as the name of a file.
For example, while.m is not a valid file name because while is one of
MATLAB's reserved words.
When declare an m-file function, the m-file must be the same name as the
function or MATLAB will not be able to run it. For example, if you declare a
function called 'factorial':
function Y = factorial(X)
It must be saved as "factorial.m" in order to use it
8-Feb-21
8
4
08/02/2021
8-Feb-21
9
10
5
08/02/2021
8-Feb-21
11
11
12
6
08/02/2021
13
8-Feb-21
14
14
7
08/02/2021
8-Feb-21
15
15
Example: The following are computations executed using the command window of MATLAB
16
8
08/02/2021
Numerical operands example, 3 < 5 means “3 less than 5,” which is conceptually a true
expression. However, in MATLAB, as in many programming languages, logical true is
represented by the integer 1, and logical false is represented by the integer 0. So, the
expression 3 < 5 actually has the value 1 in MATLAB.
Example in MATLAB command MATLAB has a function xor, which is the
window demonstrates the values of exclusive or function. It returns logical true if one
the expressions logical operators (and only one) of the arguments is true. Example:
17
MATLAB Operators
Table 2.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 2.4(b).
2.4(a) Logical operators Table 2.4 (b): Truth table for logical operators
Table 2.5 shows the rules for the operators covered so far, in the order of precedence
Table 2.5: Operator precedence rules
8-Feb-21
18
18
9
08/02/2021
Predefined Constants
Variables are used to store values that can change, or that are not known ahead of time.
Most languages have the capacity to store constants, which are values that are known ahead
of time, and cannot possibly change.
MATLAB has several predefined special constants. Examples are pi represents π, while Inf
stands for ∞, other predefined constants are illustrated in Table 2.6.
Inf : means a number so large that MATLAB cannot
Table 2.6 Predefined special constants represent it. Example: typing 5/0 will generates Inf.
NaN: indicates an undefined numerical result such
as that obtained by typing 0/0.
eps is the smallest number which, when added to 1
by the computer, creates a number greater than 1
[usually indicates the accuracy of computations].
The symbols i and j denote the imaginary unit, used
to represent complex numbers, such as y = 7 + 2i
Note: 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 a8-Feb-21
good practice
19
19
20
10
08/02/2021
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
8-Feb-21
%} 21
21
8-Feb-21
22
22
11
08/02/2021
8-Feb-21
23
23
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 ”.
The “fprintf ” stands for “formatted printing to a file” and it requires at least one argument. It
allow writing of information to the screen for the user to see.
Its first argument is a format string, which is a string that specifies the way in which printing
is to be done (spacing, number of decimal places 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 fifteen.
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 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:
8-Feb-21
24
24
12
08/02/2021
In the earlier example, the %d, %.2f, and %5.2f are known as conversion characters.
The percent symbol, “%”, and the characters immediately after 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, 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, 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"
8-Feb-21
25
25
8-Feb-21
26
26
13
08/02/2021
27
Table 3.1 Numeric data types and their range Each of these functions takes an array as an
of values 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
Note: If a conversion
function is given a value
outside its range, it will
The word int embedded in all except two, the return the value that lies at
names means “integer”; a leading “u” means the closest end of its range.
unsigned, so uint means “unsigned integer”. For example:
28
14
08/02/2021
29
30
15
08/02/2021
31
ADE 13/30GC1000 The cell may be constructed using the MATLAB statement:
ELE447 Student = {‘ADE’, ‘13/30GC1000’; {‘ELE447’;’ELE562’},
25 45
ELE562 22 50 [25,45; 22,50]}
32
16
08/02/2021
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, curly brackets {} are used; if
the cell element is in another cell, round brackets () are used.
For example
8-Feb-21
33
33
34
17
08/02/2021
35
This can be accomplished as follows The data of the second student can be viewed as follows:
>>student(2)
name: ‘CHIKE’
matric_no : ‘13/30GC1001’
email :
‘chike@unilorin.edu.ng’
age: 23
The elements of the struct student can
be viewed by typing the command: Using Struct Function
>>student As an alternative to assignment statement, structs can
>>student be constructed using the struct function which
name: ‘ADE’ preallocates a struct array. To build a struct array
matric_no : ‘13/30GC1000’
email : ‘ade@unilorin.edu.ng’ named str_array, the syntax is:
age: 21 str_array = struct(‘field1’,’values1’, ‘field2’,
‘values2’, ‘field3’, ‘values3’, . . .). For example:
To add a second student to the database,
a subscript is enclosed in round brackets >>student = struct(‘name’,‘ADE’, ‘matric_no’ ,
‘13/30GC1000’,‘email’, ‘ade@unilorin.edu.ng’, ‘age’, 21)
after the struct’s name: student=
student(2).name = ‘CHIKE’; name: ‘ADE’
student(2).matric_no = ‘13/30GC1001’; matric_no : ‘13/30GC1000’
student(2).email = ‘chike@unilorin.edu.ng’; email : ‘ade@unilorin.edu.ng’
student(2).age
8-Feb-21 = 23; age: 21
36
36
18
08/02/2021
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: Table 3.5: Some struct functions
>> student = rmfield(student, Function Description
‘email’) names = Returns the field names associated
student=
fieldnames(student) with the struct array student
name: ‘ADE’
matric_no : ‘13/30GC1000’ isfield(student, Returns 1 if ‘this_field’ is the name
age: 21 ‘this_field’) 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.
Table 3.5 illustrates other functions student = Removes the field ‘this_field’ from
that can be used with struct student rmfield(student, the struct array student
and their descriptions. Student is ‘this_field’)
variable name. student = struct(‘ Creates a struct array student with
field1’,’values1’, ... the fields ‘field1’, ‘field2’, . . .
8-Feb-21 ‘field2’, ‘value2’, having the values ‘value1’,
‘field3’, ‘value3’, . . .) ‘value2’, ... 37
37
(II) Vector: A vector in MATLAB is simply a matrix with exactly one column or exactly one
row. A variable with exactly one row is called a row vector while a variable containing exactly
one column is called a column 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]
8-Feb-21
or A = [1 3 5] and
B = [1;3;5] 38
38
19
08/02/2021
If the spacing between the elements is not 1, then the spacing has to be specify. 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/elements 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:
In command window:
1 2 In MATLAB, matrix A is entered as:
>>A = [1,2;3,4;5,6]
A 3 4 A = [1,2,;3,4;5,6] A= 1 2
5 6 3 4
5 6
8-Feb-21
39
39
40
20
08/02/2021
41
42
21
08/02/2021
Consider the following matrices To delete the second row of matrix A, type
0 0 0 0 0 0 >>A([2],:)=[]
1 2 7 11
0 0 0 0 0 0 A 3 4 9 12 >>A = [1, 2, 7, 11; 3, 4, 9, 12; 5, 6, 10, 13]
P
0 0 0 0 0 0 5 6 10 13 >> A([2], :) = []
0 0 0 0 0 0 A=
1 2 7 11
It is possible to assign new values to 5 6 10 13
part/entire block in matrix P as follows
Similarly, to delete the third column of matrix
>> P = [0,0,0,0,0,0;0,0,0,0,0,0 A, type : >>A(:,[3]) = []
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]; To delete variable A from memory, one may
>> P(2:4,2:5) = A type >>clear A
P=
0 0 0 0 0 0
0 1 2 7 11 0 To transpose a matrix and creating complex
0 3 4 9 12 0 conjugates, the operator “ ‘ ” is used.
0 5 6 10 13 0
To transpose a matrix without creating complex
Assuming matrix A is as conjugates, the operator “ .‘ ” is used.
Assuming matrix A is:
1 2 7 11
A 8-Feb-21
3 4 9 12 1 j 2 3 j
A
5 6 10 13
3 14 j 43
43
44
22
08/02/2021
45
Work Example
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 a step of 2 A, write a MATLAB
8-Feb-21
program to generate a table of current, voltage and power dissipation. 46
46
23
08/02/2021
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')
47
48
24
08/02/2021
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 B
while the left division A\B is algebraically equivalent to
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.
8-Feb-21
To find A2, type A^2
49
49
25