ELE 562 Slide-Final
ELE 562 Slide-Final
January, 2021
ELE 562
Course Outline
15-Mar-21
2
1
15/03/2021
MATLAB
2
15/03/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
15-Mar-21 and their class, that is the type of variable.
6
3
15/03/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
15-Mar-21
8
4
15/03/2021
15-Mar-21
9
5
15/03/2021
15-Mar-21
11
6
15/03/2021
15-Mar-21
14
7
15/03/2021
15-Mar-21
15
Example: The following are computations executed using the command window of MATLAB
8
15/03/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:
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
15-Mar-21
18
9
15/03/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 a15-Mar-21
good practice
19
10
15/03/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
15-Mar-21
%} 21
15-Mar-21
22
11
15/03/2021
15-Mar-21
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:
15-Mar-21
24
12
15/03/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"
15-Mar-21
25
15-Mar-21
26
13
15/03/2021
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:
14
15/03/2021
15
15/03/2021
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]}
16
15/03/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
15-Mar-21
33
17
15/03/2021
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 :
‘[email protected]’
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 : ‘[email protected]’ 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’, ‘[email protected]’, ‘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 = ‘[email protected]’; email : ‘[email protected]’
student(2).age
15-Mar-21 = 23; age: 21
36
18
15/03/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’, . . .
15-Mar-21 ‘field2’, ‘value2’, having the values ‘value1’,
‘field3’, ‘value3’, . . .) ‘value2’, ... 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]
15-Mar-21
or A = [1 3 5] and
B = [1;3;5] 38
19
15/03/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
15-Mar-21
39
20
15/03/2021
21
15/03/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 15-Mar-21
3 4 9 12 1 j 2 3 j
A
5 6 10 13
3 14 j 43
22
15/03/2021
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
15-Mar-21
program to generate a table of current, voltage and power dissipation. 46
23
15/03/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')
24
15/03/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.
15-Mar-21
To find A2, type A^2
49
MATLAB has some 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
25
15/03/2021
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];
When this program is run, it
if x < 0
gives the result
disp('Some of the elements of x are negative. ')
y=
else
2 0 + 3.000i 5
y = sqrt(x)
end
15-Mar-21
51
Any of 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
Note15-Mar-21
that the elseif statement does not require a separate end statement. 52
26
15/03/2021
Example
A 3-bit analogue to digital converter, with an analog input x and digital output y, is represented
by the equation:
y=0 x< -2.5 y=4 0.5 ≤ x < 1.5
=1 -2.5 ≤ x < -1.5 =5 1.5 ≤ x < 2.5
=2 -1.5 ≤ x < -0.5 =6 2.5 ≤ x < 3.5
=3 -0.5 ≤ x < 0.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”
15-Mar-21
53
%{
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)
%} (b) The function “analog_to_digital” is
called using the given analog inputs x1, x2,
function Y_dig = analog_to_digital (X_analog)
and x3 as follows
if X_analog < -2.5
Y_dig = 0; (i) x1 = -1.25
elseif X_analog >= -2.5 & X_analog < -1.5 y1 = analog_to_digital (x1)
Y_dig = 1; (ii) x2 = 2.57
elseif X_analog >= -1.5 & X_analog < -0.5 y2 = analog_to_digital (x2)
Y_dig = 2;
elseif X_analog >= -0.5 & X_analog < 0.5 (iii) x3 = 6.0
Y_dig = 3; y3 = analog_to_digital (x3)
elseif X_analog >= 0.5 & X_analog < 1.5
Y_dig = 4; (c) the results obtained are
elseif X_analog >= 1.5 & X_analog < 2.5
Y_dig = 5;
y1 =
elseif X_analog >= 2.5 & X_analog < 3.5 2
Y_dig = 6; y2 =
else 6
Y_dig = 7;
y3 =
end
Y_dig;15-Mar-21 7
end 54
27
15/03/2021
The loop variable k is initially assigned the value 5, and x is calculated from x = k^2. Each
successive
15-Mar-21 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. 55
Example
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); The result obtained after running
for r = 1:5 the program is:
for c = 1:5
if (r > 1) & (c > 1) % reserve r1 & C1 1 1 1 1 1
s = A(r-1,c) + A(r,c-1); 1 2 3 4 5
if s < 20
1 3 6 10 15
A(r,c) = s; % assign s to A indices
1 4 10 10 15
else
A(r,c) = max(A(r-1,c),A(r,c-1));
1 5 15 15 15
end
end
end
end
15-Mar-21
disp(A)
56
28
15/03/2021
2 10 4
Example
Consider the array A given as 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]; The result obtained after
for m = 1:size(A) running the program is:
for n = 1:size(A)
if A(m,n) >= 0 B=
B(m,n) = sqrt(A(m,n));
else 48 40 2
B(m,n) = A(m,n) + 50; 4 30 7
end 9 8 42
end
end 15-Mar-21
disp(B) 57
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. x = 5;
while x < 25
disp(x)
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
15-Mar-21
program continues to execute any statements following the end statement. 58
29
15/03/2021
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
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;
The result obtained after
k = 0;
running the program is:
while total < 1e+4
k = k + 1;
total = 5*k^2 - 2*k + total; The number of terms is:
end 18
disp('The number of terms is: ') The sum is:
disp(k) 10203
disp('The sum is: ')
15-Mar-21
disp(total) 59
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
15-Mar-21
the end statement. 60
30
15/03/2021
31
15/03/2021
32
15/03/2021
One of the outstanding strengths of MATLAB is its capability for graphical visualization of
computational results.
MATLAB has available simple but powerful graphical functions. MATLAB is thus able to
represent ordinary functions in two-dimensional plots (xy plots) and functions of two
variables in three-dimensional plots with perspective (xyz plots).
Two-dimensional Plot
The plot function is by far the most commonly used graphical function. A plot can be made
from
o a data set or
o an equation
A typical xy plot and its various parts is illustrated in Fig. 6.1 and some commands used for
plotting are as follows:
o Plot: The MATLAB basic xy plotting function is written as plot(x,y). With only one
argument, say, plot(y), the plot function will plot the values in the vector y versus their
indices 1, 2, 3, . . . , and so on.
o xlabel: To label the abscissa, the syntax is xlabel(‘text’)
o ylabel: To label the ordinate, the syntax is ylabel(‘text’)
o title: To put a title at the top of the plot, the syntax is title(‘text’)
15-Mar-21
66
33
15/03/2021
Note that the order of xlabel, ylabel, and title commands does not matter but they must be placed after
the plot command, either on separate lines using ellipses or on the same line separated by commas.
Data symbol: When data are plotted, each data point is plotted with a data symbol, or point
marker, such as the small circles shown in Fig. 6.1.
15-Mar-21
Fig. 6.1 A typical xy plot 67
Table 6.1 Specifiers for data markers, line types, and colours
Data markers Line types Colors
Dot (.) . Solid line - Black k
Asterisk (*) * Dashed line - - Blue b
Cross (x) x Dash-dotted line -.- Cyan c
Circle (o) o Dotted line .. Green g
Plus sign (+) + Magenta m
Square (□) s Red r
Diamond (◊) d White w
Five-pointed star ( ) p Yellow y
The plot(x,y) function in MATLAB automatically selects a tick-mark spacing for each axis
and places appropriate tick labels. This feature is called autoscaling
Axis: the axis command can be used to override the MATLAB selections for the axis limits.
The syntax is axis ([xmin xmax ymin ymax]).
15-Mar-21
68
34
15/03/2021
Subplot: the subplot command is used to plot several smaller “subplots” in the same figure.
The syntax is subplot(m,n,p).
This command divides the Figure window into an array of rectangular panes with m rows and
n columns. The variable p tells MATLAB to place the output of the plot command following
the subplot command into the pth pane.
For example, subplot(3,2,5) creates an array of six panes, three panes deep and two panes
across, and directs the next plot to appear in the fifth pane (in the bottom left corner).
For example, the following script file is used to construct Fig. 6.2, which shows the plot of the
functions
y = e-1.2x sin(10x + 5) for 0 ≤ x ≤ 5 and
y = |x3 - 100| for -6 ≤ x ≤6.
x = 0:0.01:5;
y = exp(-1.2*x).*sin(10*x+5);
subplot(1,2,1)
plot(x,y),xlabel('x'),ylabel('y'),a
xis([0 5 -1 1])
x = -6:0.01:6;
y = abs(x.^3-100);
subplot(1,2,2)
plot(x,y),xlabel('x'),ylabel('y'),a Fig. 6.2: Illustration of subplot command
15-Mar-21
xis([-6 6 0 350])
69
Overlay Plots: Assuming a matrix A has m rows and n columns, the following variants of
the MATLAB basic plotting functions plot(x,y) and plot(y) can be used to create overlay
plots:
plot(A) plots the columns of A versus their indices and generates n curves.
plot(x,A) plots the matrix A versus the vector x, where x is either a row vector or a
column vector and A is a matrix with m rows and n columns.
If the length of x is m, then each column of A is plotted versus the vector x.
There will be as many curves as there are columns of A.
If x has length n, then each row of A is plotted versus the vector x. There will be
as many curves as there are rows of A.
plot(A,x) plots the vector x versus the matrix A.
If the length of x is m, then x is plotted versus the columns of A. There will be
as many curves as there are columns of A.
If the length of x is n, then x is plotted versus the rows of A. There will be as
many curves as there are rows of A.
plot(A,B) plots the columns of the matrix B versus the columns of the matrix A.
1 7 1 4
For example, if matrices A and B are given as 2 8 2 5
A B
3 9 3 6
15-Mar-21
4 10 4
7 70
35
15/03/2021
y
A = [1,7;2,8;3,9;4,10];
B = [1,4;2,5;3,6;4,7];
plot(A,B)
xlabel('x'), ylabel('y')
Fig. 6.3: Plotting matrix B columns against the columns in matrix A
15-Mar-21
Fig. 6.4: Plotting a complex number
71
36
15/03/2021
Logarithmic Plots
Logarithmic scales abbreviated as log scales are widely used to
represent a data set that covers a wide range of values and
identify certain trends in data.
It is important to remember the following points when using log scales:
i. Negative numbers can not be plotted on a log scale because the logarithm of a
negative number is not defined as a real number.
ii. Number 0 can not be plotted on a log scale because log100 = ln 0 = -∞.
MATLAB has three commands for generating plots having log scales. The appropriate
command depends on which axis must have a log scale. The commands are:
i. loglog(x,y) : both x and y scales are logarithmic.
ii. semilogx(x,y): the x scale is logarithmic and the y scale is rectilinear.
iii. semilogy(x,y): the y scale is logarithmic and the x scale is rectilinear.
The following script demonstrates the use of the logarithmic plotting functions and Fig. 6.6
illustrates the corresponding graph plotted
15-Mar-21
73
x1 = 0:0.01:3; y1 = 25*exp(0.5*x1); y2 =
40*(1.7.^x1);
x2 = logspace(-1,1,500); y3 = 15*x2.^(0.37);
subplot(1,2,1),semilogy(x1,y1,x1,y2, '--
'),...
legend ('y = 25e^{0.5x}', 'y = 40(1.7)
^x'),...
xlabel('x'),ylabel('y'),grid,...
subplot(1,2,2),loglog(x2,y3),legend('y =
15x^{0.37}'),...
xlabel('x'),ylabel('y'),grid
37
15/03/2021
The Table 6.2 contains some other 2D plotting functions. The following script demonstrates
the use of some of these special plotting commands while Fig. 6.7 illustrates the
corresponding graphs generated. stairs(x,y)
x=linspace(0,2*pi,14) title('Stairs plot'), xlabel('x'),
y=sin(x); ylabel('y')
subplot(1,3,1) subplot(1,3,3)
bar(x,y) stem(x,y)
title('Bar plot'), xlabel('x'), title('Stem plot'), xlabel('x'),
ylabel('y') ylabel('y')
subplot(1,3,2)
15-Mar-21
75
2
To demonstrate the polar plot, Consider the expression r
1 0.5 cos
where r denotes distance and θ denotes angle.
The following script illustrates how the polar plot of the
expression can be realised while Fig. 6.8 shows the
corresponding graph generated.
theta = 0:pi/90:2*pi;
r = 2./(1-0.5*cos(theta));
polar(theta,r),title('Polar plot')
Example
Assuming that the Cartesian coordinates (x,y) can Fig. 6.8: Demonstration of polar plot
be converted to an equivalent polar coordinates
(r,θ) by applying the following expressions:
r x2 y2 tan 1 y x
Write15-Mar-21
a MATLAB script that converts the cartesian coordinates in Table 6.3 into polar
coordinates and execute the polar plot. 76
38
15/03/2021
Solution
points = [1 2; 4 3; 1 1; 4 0; 9 1];
r = sqrt(points(:,1).^2 + points(:,2).^2);
Fig. 6.9: Polar plot
thetha = atan(points(:,2)./points(:,1));
polar(thetha,r)
15-Mar-21
77
Three-dimensional Plot
MATLAB provides some functions for creating three-dimensional plots which includes
- line plots
- surface plots, and
- contour plots
Line Plot
Lines in three-dimensional space can be plotted with the plot3 function. Its syntax is:
plot3(x,y,z)
For example, consider the following equations
x = e-0.005tsin t
y = e-0.005tcos t
z=t
0 ≤ t ≤ 10π
The following script can be used to realize the 3D-line
plot of the equations and the corresponding graph
generated is illustrated in Fig. 6.10
Fig. 6.10: Demonstration of 3D-line plot
t = 0:pi/50:10*pi;
plot3(exp(-0.05*t).*sin(t),exp(-0.05*t).*cos(t),t)
xlabel('x'),ylabel('y'),zlabel('z'),grid 78
39
15/03/2021
z
Consider the expression
2
x y 2 y 2
z xe
for -2 ≤ x ≤ 2 and -2 ≤ y ≤ 2
Fig. 6.11 Demonstration of surface mesh plot
The following script can be used to
realize the surface mesh plot of the The surf and surfc functions are similar to mesh and
expression and the corresponding graph meshc except that the former create a shaded surface
15-Mar-21
generated is illustrated in Fig. 6.11 plot.
79
x=linspace(-5,5,41)';
y=linspace(0,10,41)';
[X,Y]=meshgrid(x,y); Fig. 6.12: Demonstration of surface mesh plot
z=1./(1+(X+0.5*Y).^2);
surf(x,y,z)
xlabel('x'), ylabel('y') ,zlabel('z')
15-Mar-21
80
40
15/03/2021
Contour Plot
Contour plots provides a means of illustrating regions of constant elevation or depression in a
graph. The syntax is
contour(x,y,z)
This function is used the same way as the mesh function; that is, first use the meshgrid
function to generate the grid and then generate the function values.
Recall that the surface mesh plot for the expression
2
x y 2 y 2
z xe
for -2 ≤ x ≤ 2 and -2 ≤ y ≤ 2 was
illustrated in Fig. 6.11. The corresponding
contour plot illustrated in Fig. 6.13 can be
realized using the following script:
[x,y] = meshgrid(-2:0.1:2);
z = x.*exp(-((x-y.^2).^2+y.^2));
contour(x,y,z),xlabel('x'),ylabel('y')
15-Mar-21
82
41
15/03/2021
7.0 Polynomials
For example, the vector [4,-8,7,-5] represents the polynomial 4x3 - 8x2 +7x - 5.
Polynomial Roots
Polynomial roots can be found with the function:
roots(a)
where a is the array containing the polynomial coefficients.
For example, to obtain the roots of the polynomial x3 +12x2 + 45x + 50 = 0
It can be done in MATLAB as follows:
15-Mar-21
83
Polynomials Cont`d
Polynomial Coefficients
To determine the coefficients of the polynomial whose roots are specified by the
array r, the syntax is:
poly(r)
The result is a row array that contains the polynomial’s coefficients.
For example, to find the polynomial whose roots are 1 and 3 5i
It can be done as follows:
If the polynomials are of different degrees, add zeros to the coefficient array of the lower-
degree
15-Mar-21
polynomial.
84
42
15/03/2021
Polynomials Cont`d
Polynomials Cont`d
43
15/03/2021
Polynomials Cont`d
OR
>> f = polyval([9,-5,3,7],[0:2:10]);
evaluations = f'
evaluations =
7
65
515
1789
4319
8537
15-Mar-21
87
Polynomials Cont`d
Polynomial Evaluation
The polyval(a,x) function evaluates a polynomial at specified values of its independent
variable x, which can be a matrix or a vector.
The polynomial’s coefficient array is denoted by a. The result is the same size as x.
For example, the following illustrates how to evaluate the polynomial f(x) = 9x3 - 5x2
+ 3x + 7 at the points x = 0, 2, 4, . . . , 10
resulting vector f contains six values that correspond to f(0), f(2), f(4), . . . , f(10).
The 15-Mar-21
88
44
15/03/2021
15-Mar-21
89
45