You are on page 1of 43

UNIVERSITI MALAYSIA PERLIS

COURSE NAME ELECTRICAL ENGINEERING SKILLS


COURSE CODE EDJ12002 LAB NO. 5

LAB MODULE

MATLAB

LEVEL OF COMPLEXITY

1 2 3 4 5 6

KNOWLEDGE COMPREHENSION APPLICATION ANALYSIS EVALUATION SYNTHESIS

√ √ √
Electrical Engineering Skills (EDJ 12002) Laboratory Manual

CONTENT

PREFACE

INTRODUCTION

LAB 1: Introduction to MatLAB…………………………………………………………

LAB 2: Scalars, Vectors & Matrices……………………………………………………….

LAB 3: MatLAB Plotting…………………………………………………………………..

LAB 4: Polynomials………………………………………………………………………..

MATLAB APPENDIX

©2022 Universiti Malaysia Perlis (UniMAP) 2


Electrical Engineering Skills (EDJ 12002) Laboratory Manual

LAB 1 INTRODUCTION TO MATLAB

OBJECTIVES

After completing this lab you should know about MATLAB desktop, and how to do a few
trivial calculations. You also should know how to create M-File scripts using a simple list
of MATLAB commands.

INTRODUCTION

 MATLAB is an interactive system for doing numerical computations.


 A numerical analyst called Cleve Moler wrote the first version of Matlab (MATrix
LABoratories) in the 1970s. It has since evolved into a successful commercial
software package.
 Matlab relieves you a lot of the mundane tasks associated with solving problems
numerically. This allows you to spend more time thinking, and encourages you to
experiment.
 Matlab makes use of highly respected algorithms and hence you can be
confident about your results.
 Powerful operations can be performed using just one or two commands.
 You can build up your own set of functions for a particular application.
 Excellent graphics facilities are available, and the pictures can be inserted in
LATEX and Word documents.

1.1 THE MATLAB DESKTOP

When you start MATLAB version 6, a special window called the MATLAB desktop
appears. The default configuration of the MATLAB desktop is shown in Figure 1. It
integrates many tools for managing files, variables, and applications within the MATLAB
environment.
The major tools within or accessible from the MATLAB desktop are the following:

 The Command Window


 The Command History Window
 Launch Pad
 Figure Windows.
 Workspace Browser and Array Editor.
 Help Browser.
 Current Directory Browser.

©2022 Universiti Malaysia Perlis (UniMAP) 3


Electrical Engineering Skills (EDJ 12002) Laboratory Manual

Figure 1.1 The MATLAB Desktop

1.1.1 THE COMMAND WINDOW

The right hand side of the MATLAB desktop contains the Command Window. A user can
interactive commands at the command prompt ( >> ) in the Command Window, and they
will be executed on the spot.

As an example of a simple interactive calculation, suppose you want to calculate the


area of a circle with a radius of 2.5m. This can be done in the MATLAB command
prompt by typing:

>> area = pi * 2.5^2


area =
19.6350

MATLAB calculates the answer as soon as the Enter key is pressed and stores the
answer in a variable (really a 1x1 array) called area. The contents of the variable are
displayed in the Command Window as shown in Figure 1.2, and the variable can be
used in further calculations.

©2022 Universiti Malaysia Perlis (UniMAP) 4


Electrical Engineering Skills (EDJ 12002) Laboratory Manual

Figure 1.2 The Command Window

If a statement is too long to type on a single line, it may be continued on


successive lines by typing an ellipsis (…) at the end of the first line, and then continuing
on the next line. For example, the following two statements are identical.

X1 = 1 + 1/2 + 1/3 + 1/4 + 1/5 + 1/6;

and

X2 = 1 + 1/2 + 1/3 + 1/4 …


+ 1/5 + 1/6;

Instead of typing commands directly in the Command Window, a series of commands


may be placed into a file, and the entire file may be executed by typing its name in the
Command Window. Such files are called script files. Script files (and functions) are also
known as M-Files because they have a file extension of “.m”

1.1.2 THE COMMAND HISTORY WINDOW

The Command History Window displays a list of the commands that a user has entered
in the Command Window. The list of previous commands can extend back to previous
executions of the program. Commands remain in the list until they are deleted. To re-
execute any command, simply double-click it with the left mouse button. To delete one
or more commands from the Command History Window, select the commands and right-
click them with the mouse.

©2022 Universiti Malaysia Perlis (UniMAP) 5


Electrical Engineering Skills (EDJ 12002) Laboratory Manual

1.1.3 THE LAUNCH PAD

The Launch Pad is a special tool that collects references to the documentation,
demos, and related tools for MATLAB itself and for each toolkit that you own. The
information is organized by product, with all references listed under each product
or toolbox. Different people will have purchased different products, so the exact
contents of this window will vary from installation to installation.

Figure 1.3 shows the Launch Pad with references for the basic MATLAB product
expanded. By double clicking on one of these items, you can get help with
MATLAB, run the MATLAB demos, access the standard tools applied with the
program, or go to the MATLAB Internet website.

Figure 1.3 The Launch Pad

1.1.4 FIGURE WINDOWS

A Figure Window is used to display MATLAB graphics. A figure can be a two or


three dimensional plot of data, an image, or a GUI (Graphic User Interface). A
simple script file that calculates and plots the function sin x is shown here:

% sin_x.m: This M-file calculates and plots the function sin(x) for 0<=x<=6
x = 0:0.1:6;
y = sin(x);
plot(x,y);

When this script file is executed, MATLAB opens a Figure Window and plots the
function sin x in it. The resulting plot is shown in Figure 1.4.

©2022 Universiti Malaysia Perlis (UniMAP) 6


Electrical Engineering Skills (EDJ 12002) Laboratory Manual

Figure 1.4 MATLAB plot of sin x versus x

1.1.5 THE MATLAB WORKSPACE

A statement like

z = 10;

Creates a variable named z, stores the value 10 in it, and saves it in apart of computer
memory known as the workspace. A workspace is the collection of all the variables and
arrays that can be used by MATLAB when a particular command, M-File, or a function is
executing. All commands executed in the Command Window (and all script files
executed from the Command Window) share a common workspace, so they can all
share variables. As we will see later, MATLAB functions differ from script files that each
function has its own separate workspace.

1.1.6 THE WORKSPACE BROWSER

The contents of the current workspace can also be examined with the GUI based
Workspace Browser. The Workspace Browser appears by default in the upper left hand
corner of the desktop. It provides a graphic display of the same information as the whos
command, and the display is dynamically updated whenever the contents of the
workspace change. The Workspace Browser also allows a user to change the contents
of any variable in the workspace.

©2022 Universiti Malaysia Perlis (UniMAP) 7


Electrical Engineering Skills (EDJ 12002) Laboratory Manual

1.2 MATLAB AS CALCULATOR

The basic arithmetic operators are +, -, *, /, ^ and these are used in conjunction with
brackets: ( ). The symbol ^ is used to get exponents (powers): 2^4 = 16.
You should type in commands shown following the prompt: >>

>> 2 + 3/4*5
ans =
5.7500
>>

Is this calculation 2 + 3/(4*5) or 2 + (3/4)*5 ? MATLAB works according to the priorities:

1. quantities in brackets.
2. powers 2 + 3^2 => 2 + 9 = 11,
3. * /, working left to right (3*4/5 = 12/5)
4. + -, working left to right (3+4-5 = 7-5)

Thus, the earlier calculation was for 2+ (3/4)*5 by priority 3.

1.2.1 GENERAL SYMBOLS AND SPECIAL VARIABLES

% starts a comment in a line


; (at the end of a statement) suppresses the display of the result
… (at the end of a line) continues the statement to the next line
\ left division, e.g., 3\15 equals 15/3 and A\b gives A^(-1)b
if A is invertible. A\b is also meaningful when A is singular.
Ans default variable name of the result available to the next statement
i or j sqrt (-1)
eps machine precision
realmin the smallest positive floating point number
realmax the largest positive floating point number
inf infinity, e.g., 1/0
NaN Not-a-number, e.g. 0/0

1.2.2 NUMBERS & FORMATS

TYPE EXAMPLES
Integer 1362, -454214
Real 1.234, -10.223
Complex 3.12 – 5.3i, ( i = 1 )
Inf Infinity (result of dividing by 0)
NaN Not a Number, 0/0

©2022 Universiti Malaysia Perlis (UniMAP) 8


Electrical Engineering Skills (EDJ 12002) Laboratory Manual

The “e” notation is used for very large or very small numbers:

-1.2345e+03 = -1.2345 x 103 = -1234.5


-1.2345e-01 = -1.2345 x 10-1 = -0.12345

All computations in MATLAB are done in double precision, which means about 15
significant figures. The format – how MATLAB prints numbers – is controlled by the
“format” command. Type help format for full list. Should you wish to switch back to the
default format then format will suffice.

Command Examples of Output


>> format short 12.3456 (4-decimal places)
>> format short e 1.2345e+01
>> format long e 1.2345678901234e+01
>> format short 12.3456(4-decimal places)
>> format bank 12.34 (2-decimal places)

1.2.3 VARIABLES

>> 3 - 2^4
ans =
-13
>> ans* 5
ans =
-65

The result of the first calculation is labeled “ans” by MATLAB and is used in the second
calculation where its value is changed. We can use our own names to store numbers:

>> x = 3-2^4
x =
-13

>> y=x+5
y =
-8

so that x has the value -13 and y = -8. These can be used in subsequent calculations.
These are examples of assignment statements: values are assigned to variables. Each
variable must be assigned a value before it may be used on the right of an assignment
statement.

©2022 Universiti Malaysia Perlis (UniMAP) 9


Electrical Engineering Skills (EDJ 12002) Laboratory Manual

1.2.4 VARIABLE NAMES

Legal names consist of any combination of letters and digits, starting with a letter. These
are allowable:

Netcost, Left2Pay, x3, X3, z24f4

These are not allowable:

Net-Cost, 2Pay, %x, @sign

Use names that reflect the values they represent.


Special names: you should avoid using
eps = 2.2204e-16 = 2-54 (The largest number such that 1 + eps is
distinguishable from 1) and pi = 3.14159… = 

If you wish to do arithmetic with complex numbers, both I and j have the value 1
unless you change them

>> i,j, i = 3
ans = 0 + 1.0000i
ans = 0 + 1.0000i
i = 3

1.2.5 TRIGONOMETRICS FUNCTIONS

Those known to MATLAB are

sin, cos, tan

and their arguments should be in radians.


e.g. to work out the coordinates of a point on a circle of radius 5 centred at the origin and
having an elevation 30 0   radians:
6

>> x = 5*cos(pi/6), y = 5*sin(pi/6)


x =
4.3301
y =
2.5000

The inverse trig functions are called asin, acos, atan (as opposed to the usual arcsin or
sin1 etc.) The result is in radians.

>> acos(x/5), asin(y/5)


ans = 0.5236
ans = 0.5236

©2022 Universiti Malaysia Perlis (UniMAP) 10


Electrical Engineering Skills (EDJ 12002) Laboratory Manual

>> pi/6
ans = 0.5236

1.2.6 OTHER ELEMENTARY FUNCTIONS

These include sqrt, exp, log, log10

>> x = 9;
>> sqrt(x), exp(x), log(sqrt(x)), log10(x^2+6)
ans =
3
ans =
8.1031e+03
ans =
1.0986
ans =
1.9395

exp(x) denotes the exponential function exp( x )  e and the inverse function is log:
x

>> format long e, exp(log(9)), log(exp(9))


ans = 9.000000000000002e+00
ans =9
>> format short

and we see a tiny rounding error in the first calculation. Log10 gives logs to the base 10.

1.2.7 CREATING M-FILES

It is often easier to create a m-file containing a sequence of commands instead of typing


commands into MATLAB one at a time. That way, if you make a mistake, you can simply
reload the command file instead of typing all the commands in again. To do this, create a
text file filename.m. These files are created using a text editor. To open the text editor,
go to the File pulldown menu, choose New, then M-File. Type all the commands you
would type normally at the MATLAB prompt (>>), and save it. If you wish to include
comments in your file, start those lines with a %. In MATLAB, you can execute the script
(a list of commands) by typing in its name.

For examples, if you have a m-file name sample.m that contains the MATLAB command
sqrt(4), you will get the following results from MATLAB :

>> sample

ans =
3

©2022 Universiti Malaysia Perlis (UniMAP) 11


Electrical Engineering Skills (EDJ 12002) Laboratory Manual

TASK OF THE DAY

1. Arithmetic operations: Compute the following quantities:

1
34  1 
(i) and compare with  1  4 
3 1
4
 3 
3 1
 1 . The square root x can be calculated with the
 
(ii) 2 2
31
command sqrt(x) or x^0.5
1

(iii) Area = r 2 with r   3


 1 . (  is pi in MATLAB)

2. Exponential and logarithms: The mathematical quantities e x , ln x , and log x


are calculated with exp( x ), log( x ), and log 10 ( x ) , respectively. Calculate the
following quantities:

(i)  
e 3 , ln e 3 and log 10 ( 105 )
(ii) e 130

(iii) Solve 3 x  17 for x and check the result.

3. Trigonometry: Calculate the following quantities:

   
(i) sin  , cos  and tan 
6 2
 
(ii) sin 2  cos 2
6 6
(iii) y  cosh x  sinh 2 x with x  32
2

4. Complex numbers:

1  3i
(i)
1  3i

i
4
(ii) e

©2022 Universiti Malaysia Perlis (UniMAP) 12


Electrical Engineering Skills (EDJ 12002) Laboratory Manual

LAB 2 SCALARS, VECTORS & MATRICES

The three most common structures in MATLAB for storing numbers or groups of
numbers are scalars, vectors, and matrices.

2.1 SCALARS

A scalar is a single value, such as 2 or 6. Some examples of scalar declarations are:

>> a = 5;
>> b = 7.521;

The semicolon at the end of the statement suppresses the output to the screen. If you
omitted the semicolon your screen would look like this:

>> a=5
a =
5

2.2 VECTORS

These come in two flavours and we shall first describe row vectors: they are lists of
numbers separated by either commas or spaces. The number of entries is known as the
“length” of the vector and the entries are often referred to as “elements” of the vector.
The entries must be enclosed in square brackets.

>> v = [1 3, sqrt(5)]
v =
1.0000 3.0000 2.2361
>> length(v)
ans =
3

Spaces can be vitally important:

>> v2 = [3+ 4 5]
v2 =
7 5
>> v3 = [3 +4 5]
v3 =
3 4 5

We can do certain arithmetic operations with vectors of the same length, such as v and
v3 in the previous section.

>> v + v3
ans =
4.0000 7.0000 7.2361

©2022 Universiti Malaysia Perlis (UniMAP) 13


Electrical Engineering Skills (EDJ 12002) Laboratory Manual

>> v4 = 3*v
v4 =
3.0000 9.0000 6.7082
>> v5 = 2*v -3*v3
v5 =
-7.0000 -6.0000 -10.5279
>> v + v2
??? Error using ==> +
Matrix dimensions must agree.

i.e. the error is due to v and v2 having different lengths. A vector may be multiplied by a
scalar (a number – see v4 above), or added/subtracted to another vector of the same
length. The operations are carried out element wise. We can build row vectors from
existing ones:

>> w = [1 2 3], z = [8 9]
>> cd = [2*z, -w], sort(cd)
w =
1 2 3
z =
8 9
cd =
16 18 -1 -2 -3
ans =
-3 -2 -1 16 18

Notice the last command sorted the elements of cd into ascending order. We can also
change or look at the value of particular entries

>> w(2) = -2, w(3)


w =
1 -2 3
ans =
3

2.2.1 THE COLON NOTATION

This is a shortcut for producing row vectors:

>> 1:4
ans =
1 2 3 4
>> 3:7
ans =
3 4 5 6 7
>> 1 : -1
ans =
[]

©2022 Universiti Malaysia Perlis (UniMAP) 14


Electrical Engineering Skills (EDJ 12002) Laboratory Manual

More generally a : b : c produces a vector of entries starting with the value of a,


incrementing by the value of b until it gets to c (it will produce a value beyond c). This is
why 1:-1 produced the empty vector [].

>> 0.32 : 0.1 : 0.6


ans =
0.3200 0.4200 0.5200
>> -1.4 : -0.3 : -2
ans =
-1.4000 -1.7000 -2.0000

2.2.2 EXTRACTING BITS OF A VECTOR

>> r5 = [1 : 2 : 6, -1 : -2 : -7]
r5 =
1 3 5 -1 -3 -5 -7

To get the 3rd to 6th entries:

>> r5(3 : 6)
ans =
5 -1 -3 -5
To get alternate entries:

>> r5(1 : 2 : 7)
ans =
1 5 -3 -7

What does r5(6 : -2 : 1) give?

2.2.3 COLUMN VECTORS

These have similar constructs to row vectors. When defining them, entries area
separated by ; or “newlines”

>> c = [ 1; 3; sqrt(5) ]
c =
1.0000
3.0000
2.2631
>> c2 = [3
4
5]
c2 =
3
4
5

>> c3 = 2*c – 3*c2


c3 =
-7.0000

©2022 Universiti Malaysia Perlis (UniMAP) 15


Electrical Engineering Skills (EDJ 12002) Laboratory Manual

-6.0000
-10.5279

so column vectors may be added or subtracted provided that they have the same length.

2.2.4 TRANSPOSING

We can convert a row vector into a column vector (and vice versa) by a process called
transposing – denoted by ’.

>> w, w’, c, c’
w =
1 -2 3
ans =
1
-2
3
c =
1.0000
3.0000
2.2361
ans =
1.0000 3.0000 2.2361

>> t = w + 2*c’
t =
3.0000 4.0000 7.4721
>> T = 5*w’ – 2*c
T =
3.0000
-16.0000
10.5279

If x is a complex vector, then x’ gives the complex conjugate transpose of x.

>> x = [1 + 3i, 2 – 2i]


ans =
1.0000 + 3.0000i 2.0000 – 2.0000i
>> x’
ans =
1.0000 – 3.0000i
2.0000 + 2.0000i

Note that the components of x were defined without a * operator; this means of defining
complex numbers works even when the variable i already has a numeric value. To
obtain the plain transpose of a complex number use .’ as in

>> x.’
ans =
1.0000 + 3.0000i
2.0000 - 2.0000i

©2022 Universiti Malaysia Perlis (UniMAP) 16


Electrical Engineering Skills (EDJ 12002) Laboratory Manual

2.3 MATRICES - TWO DIMENSIONAL ARRAYS

Row and Column vectors are special cases of matrices. An m x n matrix is a rectangular
array of numbers having m rows and n columns. It is usual in a mathematical setting to
include the matrix in either round or square brackets – we shall use square ones. For
example, when m=2, n=3 we have a 2x3 matrix such as

5 7 9 
A = 1  3  7 
 

To enter such an matrix in MATLAB, we type it in row by row using the same syntax as
for vectors:

>> A = [5 7 9
1 -3 -7]
A =
5 7 9
1 -3 -7

Rows may be separated by semi-colons rather than a new line:

>> B = [-1 2 5; 9 0 5]
B =
-1 2 5
9 0 5

>> C = [0, 1; 3, -2; 4, 2]


C =
0 1
3 -2
4 2
>> D = [1:5 ; 6:10 ; 11:2:20]
D =
1 2 3 4 5
6 7 8 9 10
11 13 15 17 19

So A and B are 2x3 matrices, C is 3x2 and D is 3x5. In this context, a row vector is a 1xn
matrix and a column vector a mx1 matrix.

©2022 Universiti Malaysia Perlis (UniMAP) 17


Electrical Engineering Skills (EDJ 12002) Laboratory Manual

2.3.1 SIZE OF A MATRIX

We can get the size (dimensions) of a matrix with the command size

>> size(A), size(x)


ans =
2 3
ans =
1 2
>> size(ans)
ans =
1 2

So A is 2x3 and x is 1x2 (a column vector). The last command size(ans) shows the value
returned by size is itself a 1x2 matrix (a row vector). We can save the results for use in
subsequent calculations.

>> [r c] = size(A’), S = size(A’)


r =
3
c =
2
S =
3 2

2.3.2 TRANSPOSE OF A MATRIX

Transposing a vector changes it from a row to a column vector and vice versa. The
extension of this idea to matrices is that transposing interchanges rows with the
corresponding columns; the 1st row becomes the 1st columns, and so on.

>> D, D’
D =
1 2 3 4 5
6 7 8 9 10
11 13 15 17 19
ans =
1 6 11
2 7 13
3 8 15
4 9 17
5 10 19
>> size(D), size(D’)
ans =
3 5
ans =
5 3

©2022 Universiti Malaysia Perlis (UniMAP) 18


Electrical Engineering Skills (EDJ 12002) Laboratory Manual

2.3.3 THE IDENTITY MATRIX

The nxn identity matrix is a matrix of zeros except for having ones along its leading
diagonal (top left to bottom right). This is called eye(n) in MATLAB (since mathematically
it is usually denoted by I).

>> I = eye(3), x = [8; -4; 1], I*x


I =
1 0 0
0 1 0
0 0 1
x =
8
-4
1
ans =
8
-4
1

Notice that multiplying the 3x1 vector x by the 3x3 identity I has no effect (it is like
multiplying a number by 1)

2.3.4 EXTRACTING BITS OF MATRICES

We may extract sections from a matrix in much the same way as for a vector. Each
element of a matrix is indexed according to which row and column it belongs to. The
entry in the ith row and jth column is denoted mathematically by Ai,j and, in MATLAB, by
A(i,j). So,
>> J
J =
1 2 3 4
5 6 7 8
9 10 11 12
20 0 5 4

>> J(1,1)
ans =
1
>> J(2,3)
ans =
7
>> J(4,3)
ans =
5
>> J(4,1) = J(1,1) + 6
J =
1 2 3 4

©2022 Universiti Malaysia Perlis (UniMAP) 19


Electrical Engineering Skills (EDJ 12002) Laboratory Manual

5 6 7 8
9 10 11 12
7 0 5 4
>> J(1,1) = J(1,1) – 3*J(1,2)
J =
-5 2 3 4
5 6 7 8
9 10 11 12
7 0 5 4

In the following examples we extract i) the 3rd column, ii) the 2nd and 3rd columns, iii) the
4th row, and iv) the “central” 2x2 matrix.

>> J(:,3) %3rd column


ans =
3
7
11
5
>> J(:,2:3) %columns 2 to 3
ans =
2 3
6 7
10 11
0 5

>> J(4,:) %4th row


ans =
7 0 5 4
>> J(2:3,2:3) % rows 2 to 3 & cols 2 to 3
ans =
6 7
10 11

Thus ,: on its own refers to the entire column or row depending on whether it is the first
or the second index.

2.3.5 DOT PRODUCT OF MATRICES (.*)

The dot product works as for vectors: corresponding elements are multiplied together –
so the matrices involved must have the same size.

>> A, B
A =
5 7 9
1 -3 -7
B =
-1 2 5
9 0 5
>> A.*B

©2022 Universiti Malaysia Perlis (UniMAP) 20


Electrical Engineering Skills (EDJ 12002) Laboratory Manual

ans =
-5 14 45
9 0 -35
>> A.*C
??? Error using ==> .*
Matrix dimensions must agree.
>> A.*C’
ans =
0 21 36
1 6 -14

2.3.6 MATRIX – VECTOR PRODUCTS

We turn next to the definition of the product of a matrix with a vector. This product is only
defined for column vectors that have the same number of entries as the matrix has
columns. So, if A is an mxn matrix and x is a column vector of length n, then the matrix-
vector A x is legal. An mxn matrix times an nx1 matrix  a mx1 matrix. We visualized A
as being made up of m row vectors stacked on top of each other, then the product
corresponds to taking the scalar product of each row of A with the vector x . The result
is a column vector with m entries.

 8 
5 7 9   4 
Ax = 1  3  7   
   1 
 5 x 8  7 x ( 4 )  9 x 1 
= 1 x 8  ( 3 ) x( 4 )  ( 7 ) x 1
 
 21
= 13
 

It is somewhat easier in MATLAB:

>> A = [5 7 9; 1 -3 -7]
A =
5 7 9
1 -3 -7
>> x = [8; -4; 1]
x =
8
-4
1
>> A*x
ans =
21
13

Unlike multiplication in arithmetic, A*x is not the same as x*A.

©2022 Universiti Malaysia Perlis (UniMAP) 21


Electrical Engineering Skills (EDJ 12002) Laboratory Manual

2.3.7 MATRIX – MATRIX PRODUCTS

To form the product of an mxn matrix A and a nxp matrix B, written as AB, we visualised
the first matrix (A) as being composed of m row vectors of length n stacked on top of
each other while the second (B) is visualised as being made up of p column vectors of
length n:
      
   
  
A = m rows   , B=  
     
 
      
   

p columns

The entry in the ith row and jth column of the product is then the scalar product of the ith
row of A with the jth column of B. The product is an mxp matrix:

( m x n ) times ( n x p )  ( m x p )

This is a more general example:

©2022 Universiti Malaysia Perlis (UniMAP) 22


Electrical Engineering Skills (EDJ 12002) Laboratory Manual

TASK OF THE DAY

 1 2 3
1.
 
For a matrix A  4 5 6 , determined the following:
 
7 8 9 

(i) x, where x is the transpose of the first row of A.


(ii) The products of row vector and column vector of x which gives a
scalar.
(iii) The products of row vector and column vector of x which gives a
matrix.

2. Assume that a, b, c and d are defined as follows.

1 0  1 2
a  b 
 2 1  0 1

 3
c  d5
2

What is the result of each of the following:

(i) Addition between a and b.


(ii) Element by element multiplication of a and b.
(iii) Matrix multiplication of a and b.
(iv) Matrix multiplication of a and c.
(v) Matrix addition between a and c.

 1 2 1  1
3.
 
Solve for x in the equation Ax  B , where A  2 3 2 and B 
 1
   
  1 0 1  0 
Hint: x  A1 B

©2022 Universiti Malaysia Perlis (UniMAP) 23


Electrical Engineering Skills (EDJ 12002) Laboratory Manual

LAB 3 MATLAB PLOTTING

OBJECTIVES

There are many times when a visual presentation of data is useful. MATLAB has many
helpful functions to display data visually. In this lab, you will be introduced to the basics
of MATLAB plotting.

3.1 PLOT OF A SINGLE FUNCTION

Most of the plotting that will be done in this lab will be done with the use of the plot
command. The syntax for the plot command is:

plot ( x , y )

where
x is a vector representing the abscissa ( x-axis )
y is a vector representing the ordinate ( y-axis )

Suppose we wish to plot a graph of y  sin 3x for 0  x  1 . We do this by sampling


the function at a sufficiently large number of points and then joining up the points (x,y) by
straight lines, Suppose we take N+1 points equally spaced a distance h apart:

>> N = 10; h = 1/N; x = 0:h:1;

defines the set of points x  0 , h,2h,...,1  h,1 . The corresponding y values are
computed by:

>> y = sin(3*pi*x); (1)

and finally plot the points with

>> plot (x,y)

For comparison, we change the value of N to 100, and then make a comparison.

For examples, type the following commands to plot sin( 2t ) for  5  t  5 :

>> t = -5:.01:5;
>> y = sin(2*pi*t); (2)
>> plot(t,y);

Then you should see a plot of a sine function that has a magnitude of 1 and a frequency
of 1 rad/s.

©2022 Universiti Malaysia Perlis (UniMAP) 24


Electrical Engineering Skills (EDJ 12002) Laboratory Manual

3.2 PLOTTING – TITLES & LABELS

To put a title and label the axes, we use

>> title(‘Graph of y  sin 3x ’)


>> xlabel(‘x axis’)
>> ylabel(‘y axis’)

The strings enclosed in single quotes, can be anything of our choosing. Normally, the
axis labels include the type of measurement represented by the axis, as well as the unit
of measurement, when applicable.

3.3 GRID

A dotted grid maybe added by

>> grid

This can be removed either grid again, or grid off.

3.4 CHANGING PLOTTING COLOURS & LINE STYLES

The default is to plot solid lines. A solid white line is produced by

>> plot(x,y,’-w’)

The third argument is a string whose first character specifies the colour(optional and the
second line style. The options for colours and styles are:

Colours Line Styles


y yellow . point
m magenta o circle
c cyan x x-mark
r red + plus
g green - solid
b blue * star
w white : dotted
k black -. dash dotted
-- dashed

©2022 Universiti Malaysia Perlis (UniMAP) 25


Electrical Engineering Skills (EDJ 12002) Laboratory Manual

3.5 PLOTS OF MULTIPLE SINGLE FUNCTIONS

More than one function may be plotted on the same graph. The syntax to graph multiple
plots is:

plot ( x 1 , y 1 , x 2 , y 2 ,..., x n , y n )

Type the follow commands to plot the previous sine function (case 2) together with
cos( 2x ) :

>> z = cos(2*pi*x);
>> plot(x,y,t,z);

Refered to case 1, several graphs may be drawn on the same figure as in

>> plot(x,y,’m-‘, t, cos(3*pi*x), ’g--‘)

A descriptive legend may be included with

>> legend(‘Sin curve’,’Cos curve’)

which will give a list of line-styles, as they appeared in the plot command, followed by a
brief description. MATLAB fits the legend in suitable position, so as not to conceal the
graphs whenever possible. The legend may be moved manually by dragging it with the
mouse.

3.6 PLOTS OF COMPLEX NUMBERS

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. If y is complex, plot(y) plots the imaginary parts
versus the real parts. Thus plot(y) in this case is equivalent to plot (real(y),image (y)).
This situation is the only time when the plot function handles the imaginary parts, in all
other variants of plot function, it ignores the imaginary parts. For example:

>> z = 0.1 + 0.9i;


>> n = [0:0.1:10];
>> plot(z.^n), xlabel(‘Real’), ylabel(‘Imaginary’)

©2022 Universiti Malaysia Perlis (UniMAP) 26


Electrical Engineering Skills (EDJ 12002) Laboratory Manual

3.7 CHANGING DOMAIN AND RANGE OF PLOTS

The default values for the domain and range of a plot can be overridden with the axis
command. The syntax for the axis command is:

axis( v )
axis x min, x max, y min, y max
where v is a vector with the values [xmin, xmax, ymin, ymax]. Xmin and xmax define the
domain and ymin and ymax define the range of the plot.

Change the domain of the plot from  5  t  5 to    t   by typing the following:

>> axis([-pi,pi,-1,1])

3.8 ADDING TEXT TO A PLOT

It is also possible to add text to the plot. Text can be added to the plot with the text and
the gtext commands. The syntax for these commands is:

text( x , y ,' string' )


gtext(' string' )

where
x is the coordinate from the independent axis to place the text
y is the coordinate from the dependent axis to place the text
string is the text to add to the plot

The text command adds the text represented by ‘string’ at the location specified by the
coordinates (x,y). The gtext command displays the graph window with a set of
crosshairs. The mouse is used to position the crosshairs. Pressing any mouse button
causes the text to be written at the selected location.

Use the gtext command to label the different plots on the graph by typing the following
commands:

>> gtext(‘Sin(x)’)
>> gtext(‘Cos(x)’)

©2022 Universiti Malaysia Perlis (UniMAP) 27


Electrical Engineering Skills (EDJ 12002) Laboratory Manual

3.9 HOLD

A call to plot clears the graphics window before plotting the current graph. This is not
convenient if we wish to add further graphics to the figure at some later stage. To stop
the window being cleared:

>> plot(x,y,’w--‘), hold


>> plot(x,y,’gx’), hold off

“hold on” holds the current picture; “hold off” releases it (but does not clear the window,
which can be done with clf). “hold” on its own toggles the hold state.

3.10 SUBPLOT

The graphics window may be split into an mxn array of smaller windows into which we
may plot one or more graphs. The windows are counted 1 to mn row-wise, starting from
the top-left. Both hold and grid work on the current subplot. For example:

>> subplot(221), plot(x,y)


>> xlabel(‘x’),ylabel(‘sin 3 pi x’)
>> subplot(222), plot(x,cos(3*pi*x))
>> xlabel(‘x’),ylabel(‘cos 3 pi x’)
>> subplot(223), plot(x,sin(6*pi*x))
>> xlabel(‘x’),ylabel(‘sin 6 pi x’)
>> subplot(224), plot(x,cos(6*pi*x))
>> xlabel(‘x’),ylabel(‘cos 6 pi x’)

Subplot (221) (or subplot(2,2,1)) specifies that the window should be split into a 2 x 2
array and we select the first subwindow.

3.11 THE FUNCTION PLOT COMMAND

MATLAB has a “smart” command for plotting functions. The fplot command
automatically analyzes the function to be plotted and decides how many plotting points
to use so that the plot will show all the features of the function. Its syntax is:

fplot ' string' , x min x max

where
‘string’ text string that describes the function to be plotted
[ xmin xmax] specifies the minimum and maximum values of the independent
variable.

The range of the dependent variable can also be specified. In this case the syntax is

fplot ' string' ,x min x max y min y max


For example, the session

>> f = ‘cos(tan(x)) – tan(sin(x))’;


>> fplot(f,[1 2])

©2022 Universiti Malaysia Perlis (UniMAP) 28


Electrical Engineering Skills (EDJ 12002) Laboratory Manual

TASK OF THE DAY

1. Plot y  0.4 1.8 x for 0  x  52 , where y represents the height of a rocket


after launch, in miles, and x is the horizontal (downrange) distance, in miles.

2. Use the fplot and plot command to plot the function below:

tan cos( x )  sin(tan x ) for 0  x  2

3. Plot both functions in the same figure:

y  e 1.2 x sin( 10 x  5 ) for 0  x  5 ,  1  y  1


y  x  100
3
for  6  x  6 , 0  y  350

©2022 Universiti Malaysia Perlis (UniMAP) 29


Electrical Engineering Skills (EDJ 12002) Laboratory Manual

LAB 4

4.1 POLYNOMIALS

Polynomial has the form:

f x  a0 x N  a1 x N 1  a2 x N 2  ................. aN 2 x 2  a N 1 x  a N

Example

Evaluate,
f x   4 x 4  3x 2  1

for x=3.2

To find the value for f(x) for x=3.2 we can apply the polyval function.
We also need to represent the above polynomial in MATLAB format.

c = [4 0 -3 0 -1]

What we are doing above is taking the coefficients of the polynomial and put them in a
matrix c.

polyval(c,3.2)

ans=
387.7104

If you would like to find the values for f(x) over an interval of x from 0 to 5 then you can
type:
x = [0:5]
polyval(c,x)

ans =

Columns 1 through 4

-1 0 51 296

Columns 5 through 6

975 2424

©2017Universiti Malaysia Perlis (UniMAP) 30


Electrical Engineering Skills (EDJ 12002) Laboratory Manual

4.1.1 ARITHMETIC OPERATION FOR POLYNOMIALS

4.1.1.1 Addition

To add two polynomials just add up their coefficients

Example
f x   2 x 3  1
g x   3x 4  2 x 2  8

f = [2 0 0 1]
g = [3 0 -2 0 -8]

f+g
??? Error using ==> +
Matrix dimensions must agree

Thus we need to modify the matrix for f to make size similar to g

f = [0 2 0 0 1]

f+g
ans =
3 2 -2 0 -7

4.1.1.2 Subtraction

f-g
ans =
-3 2 2 0 9

4.1.1.3 Multiplication

Calculations involving multiplication is more complex thus MATLAB has offered a


functions called conv (convolution) to handle this task.

Example

Multiply the following two polynomials:

©2022 Universiti Malaysia Perlis (UniMAP) 31


Electrical Engineering Skills (EDJ 12002) Laboratory Manual

f x   2 x 5  3x 4  4 x 2  3
g x   6 x 4  5 x 2  6

Notice that unlike addition or subtraction where the matrix size must be the same, for
multiplication the sizes can be different.

conv(f,g)
ans =
12 18 -10 -39 -12 -16 -0 39 0 18

The answer obtained above represents:

12x9+18x8-10x7-39x6-12x5-16x4+39x2+18

4.1.1.4 Division

To perform a division for polynomials use deconv function.


The form for deconv is:

The result will be put in vector q and the remainder is in vector r

[q,r] = deconv(f,g)
q=
0.3333 0.5000
r=
0 0 1.6667 1.5000 2.0000 0

So, the answer is:

0.3333x + 0.5 with a remainder of,

1.6667x3 – 1.5x2 + 2x

4.1.2 ROOTS OF POLYNOMIALS

The solution to many engineering problems involves finding the roots of an equation of
the form:

y = f(x)

Where the roots are the values of x for which y is equal to zero.

Look at the following equation:

y = f(x) = 3x2+2x-1
= (3x-1)(x+1)

©2022 Universiti Malaysia Perlis (UniMAP) 32


Electrical Engineering Skills (EDJ 12002) Laboratory Manual

So the solution for the above problem is:

x = 1/3 and x = -1

MATLAB can easily find the roots by using a function called roots

First write down the coefficients in a matrix

a=[3 2 -1]

roots(a)

ans =
-1.000
0.333

The answer could also be in complex number as shown below

f(x) = x3 - 2x2 - 3x + 10

a = [ 1 -2 -3 10 ]

roots(a)

ans =
2.0000 + 1.0000i
2.0000 – 1.0000i
-2.0000

4.2 NUMERICAL INTEGRATION AND DIFFERENTIATION

4.2.1 Numerical Integration

4.2.1.1 Integration

MATLAB uses two functions to perform integration. The first function is quad, which uses
an adaptive form of Simpson’s rule. The second function is quad8 which based on
Newton-Cotes 8- panel rule. The quad8 function is better at handling functions with certain
1
types of singularities, such as 
0
x dx . Both functions print a warning message if they

detect a singularity, but an estimate of the integral is still returned.

The name refers to a function. This function can be a built-in MATLAB function like sqrt,
sin and cos or it can be a user written function. This function must be placed in quotes. A
and b are limits of the integration.

©2022 Universiti Malaysia Perlis (UniMAP) 33


Electrical Engineering Skills (EDJ 12002) Laboratory Manual

Example:

Integrate,

5
f(x) = 
0
x

We can use the built- in function which is sqrt.

q = quad(‘sqrt’,0,5)

Recursion level limit reached in quad. Singularity likely.


q=
7.4535

Notice that a singularity occurs but MATLAB still produces an estimation.


To use quad8, you can write:

q = quad8(‘sqrt’,0,5)
q=
7.4536

Example

Integrate:

3
x4  x2  4
f(x) = 
0
2
dx

First, we need to build a function for the above equation.


Write the following function.

function f=eq1(x)

f =(x.^4-x.^2-4)/2

Save the M-files as eq1.m

At the MATLAB prompt, type:

quad(‘eq1’,0,3)
ans =
13.8001

For quad8,type:

©2022 Universiti Malaysia Perlis (UniMAP) 34


Electrical Engineering Skills (EDJ 12002) Laboratory Manual

quad8(‘eq1’,0,3)
ans =
13.8000

4.2.1.2 Double Integration

The function used to numerically evaluate double integral is dblquad.


Syntax:
Result = dblquad(‘function’,inmin.inmax,outmin,outmax)

Example

 

  4 sin( x)  3x * cos( y)dxdy


0 0

First we need to write a function to store the above equation:

function w = dint(x,y)

w = 4*sin(x)-3*x*cos(y);

save the function as dint.m

result = dblquad(‘dint’,0,pi,0,pi)

result =
25.1327

or, if we would like to use quad8 in the double integral ,we could write:

result = dblquad(‘dint’,0,pi,0,pi,’quad8’)

result =
25.1327

Instead of writing a function to store the equation, you could also use inline.

eq = inline (‘4*x-3*y^2’,’x’,’y’)
result = dblquad(eq,0,1,0,1)

eq=
Inline function:
eq(x,y) = 4*x-3*y^2
result =
1

Note the use of inline above. Since the equation contains two variables, x and y, we
need to specify them as show i,e. ‘x’,’y’.

©2022 Universiti Malaysia Perlis (UniMAP) 35


Electrical Engineering Skills (EDJ 12002) Laboratory Manual

4.2.2 NUMERICAL DIFFERENTIATION

The function used for differentiation is diff.

This function computes differences between adjacent values in a vector, generating a


new vector with one less value.

Example

If , y = [2 4 6 8 10] and x = [1 2 3 4 5], then,

diff(y)
ans =
2 2 2 2
diff(x)
ans =
1 1 1 1

To obtain the derivative, we will take dy/dx :


dydx = diff(y)./diff(x)
dydx =
2 2 2 2

Example

Differentiate,
y = 3x2 at x = 2

First we need to create a matrix for x:

x = [1.9999:0.00001:2.0001]

We have picked numbers that are very close to x so that the difference between the
numbers is small and thus this will give a more accurate result.

y = 3*x.^2

dydx = diff(y)./diff(x)

dydx =

Columns 1 through 5

11.9994 11.9995 11.9995 11.9996 11.9997

Columns 6 through 10

©2022 Universiti Malaysia Perlis (UniMAP) 36


Electrical Engineering Skills (EDJ 12002) Laboratory Manual

11.9997 11.9998 11.9998 11.9999 12.0000

Columns 11 through 15

12.0000 12.0001 12.0002 12.0002 12.0003

Columns 16 through 20

12.0003 12.0004 12.0004 12.0005 12.0006

There are many answers for dydx because we have built a matrix for x. To find the value
for dydx at x = 2, first we will polyfit the above data. But check first the sizes for dydx
and x.
whos
Name Size Bytes Class

dydx 1x20 160 double array


x 1x21 168 double array
y 1x21 168 double array

The size for dydx is 1x20 while for x it is 1x21.polyfit cannot be used unless we make
the size equal.

Take out one column from x:


x = x(:,1:length(x)-1)
x=

Columns 1 through 5

1.9999 1.9999 1.9999 1.9999 1.9999

Columns 6 through 10

2.0000 2.0000 2.0000 2.0000 2.0000

Columns 11 through 15

2.0000 2.0000 2.0000 2.0000 2.0000

Columns 16 through 20

2.0001 2.0001 2.0001 2.0001 2.0001

then only you can polyfit the data:

polyfit(x,dydx,2)
ans =

©2022 Universiti Malaysia Perlis (UniMAP) 37


Electrical Engineering Skills (EDJ 12002) Laboratory Manual

0.0003 5.9990 0.0010

To get the value at x = 2

polyval(ans,2)

ans =

12.0000

The answer when differentiate the equation at x = 2 is 12.

©2022 Universiti Malaysia Perlis (UniMAP) 38


Electrical Engineering Skills (EDJ 12002) Laboratory Manual

TASK OF THE DAY

1. a) Use MATLAB to confirm that

(20x3-7x2+5x+10)(4x2+12x-3)

= 80x5+212x4-124x3+121x2+105x-30

b) Use Matlab to find the following product

(10x3-9x2-6x+12)(5x3-4x2-12x+8)

2. a) Use MATLAB to confirm that

12x3+5x2-2x+3 / 3x2-7x+4 = 4x+11

with a remainder of 59x-41

b) Use MATLAB to find the quotient and remainder of

14x3-6x2+3x+9 / 5x2+7x-4

3. a) Use MATLAB to confirm that

6x3+4x2-5 / 12x3-7x2+3x+9 = 0.7108

when x = 2

b) Use MATLAB to evaluate

8x3+9x2-7 / 10x3+5x2-3x-7

when x = 5

4. Use MATLAB to compute the resulting coefficient of the product of two


polynomials:

y = (3x6+2x4+ 2x 3 +x-9) (x10- 3x 5 +x)

5. Starting at x = -4, find an approximate root of the polynomial

P(x) = x3-2x2+3x-4

©2022 Universiti Malaysia Perlis (UniMAP) 39


Electrical Engineering Skills (EDJ 12002) Laboratory Manual

MATLAB APPENDIX

Operators and special characters

Item Description
+ Plus; addition operator
- Minus; subtraction operator
* Scalar and matrix multiplication operator
.* Array multiplication operator
^ Scalar and matrix exponentiation operator
.^ Array exponentiation operator
\ Left division operator
/ Right division operator
.\ Array left division operator
./ Array right division operator
: Colon; generates regularly spaced elements and represents an entire row
or column
() Parentheses; encloses function arguments and array indices,; overrides
precedence.
[] Brackets; encloses array elements
{} Braces; encloses cell elements
. Decimal point
… Ellipsis; line-continuation operator
, Comma; separates statements, and elements in a row of an array
; Semicolon; separates columns in an array, and suppresses display
% Percent sign; designates a comment, and specifies formatting
’ Quote sign and transpose operator
.’ Nonconjugated transpose operator
= Assignment (replacement) operator

Special variables and constants

Item Description
ans Most recent answer
eps Accuracy of floating point precision
i,j The imaginary unit  1
Inf Infinity
NaN Undefined numerical result (not a number)
pi The number 

Commands for managing a session

©2022 Universiti Malaysia Perlis (UniMAP) 40


Electrical Engineering Skills (EDJ 12002) Laboratory Manual

Item Description
clc Clears Comamnd Window
clear Removes variables from memory
exist Checks for existance of file or variable
global Declares variables to be global
help Displays help text in the Command Window
helpwin Displays help text in the Help Browser
lookfor Searches help entries for a keyword
quit Stops Matlab
who Lists current variables.
whos Lists current variables (long display)

Numeric display formats

Item Description
format short Four decimal digits
format long 16 decimal digits
format short e Five digits plus exponent
format long e 16 digits plus exponent
format bank Two decimal digits
format + Positive, negative or zero
format rat Rational approximation
format compact Suppresses some line feeds
format loose Resets to less compact display mode.

Array functions

Item Description
cat Concatenates arrays.
find Finds indices of nonzero elements
length Computes number of elements.
linspace Creates regularly spaced vector
logspace Creates logarithmically spaced vector
max Returns largest element
min Returns smallest element
size Computes array size
sort Sorts each column
sum Sums each column

Special matrices

Item Description
eye Creates an identity matrix
ones Creates an array of ones
zeros Creates an array of zeros

Exponential and logarithmic functions

©2022 Universiti Malaysia Perlis (UniMAP) 41


Electrical Engineering Skills (EDJ 12002) Laboratory Manual

Item Description
exp(x) Exponential; e x

log(x) Natural logarithm; ln x


log10(x) Common (base 10) logarithm; log x  log 10 x
sqrt(x) Square root; x

Complex functions

Item Description
abs(x) Absolute value; x
angle(x) Angle of a complex number x
conj(x) Complex conjugate of x
imag(x) Imaginary part of a complex number x
real(x) Real part of a complex number x

Trigonometric functions

Item Description
acos(x) Inverse cosine; arccos x  cos 1 x
acot(x) Inverse cotangent; arc cot x  cot 1 x
acsc(x) Inverse cosecant; arc csc x  csc 1 x
asec(x) Inverse secant; arc sec x  sec 1 x
asin(x) Inverse sin; arcsin x  sin 1 x
atan(x) Inverse tangent; arctan x  tan1 x
atan2(y,x) Four quadrant inverse tangent
cos(x) Cosine; cos x
cot(x) Cotangent; cot x
csc(x) Cosecant; csc x
sec(x) Secant; sec x
sin(x) Sine; sin x
tan(x) Tangent; tan x

Basic xy plotting commands

Item Description
axis Sets axis limits
fplot Intelligent plotting of functions.
ginput reads coordinates of the cursor position
grid Displays gridlines
plot Generats xy plot
print Prints plot or saves plot to a file
title Puts text at top of plot
xlabel Adds text label to x-axis
ylabel Adds text label to y-axis.

©2022 Universiti Malaysia Perlis (UniMAP) 42


Electrical Engineering Skills (EDJ 12002) Laboratory Manual

Plot-enhancement commands

Item Description
axes Creates axes objects
gtext Enables label placement by mouse
hold Freezes current plot
legend Legend placement by mouse
refresh Redraws current figure window
set Specifies properties of objects such as axes
subplot Creates plots in subwindows.
text Places string in figure.

Program flow control

Item Description
break Terminates execution of a loop
case Provides alternate execution paths within switch structure
continue Passes control to the next iteration of a for or while loop.
else Delineates alternate block of statements.
elseif Conditionally executes statements.
end Terminates for,while and if statements.
for Repeats statements a specific number of times.
if Executes statements conditionally.
otherwise Provides optional control within a switch structure.
switch Directs program execution by comparing input with case
expressions
while Repeats statements an indefinite number of times.

©2022 Universiti Malaysia Perlis (UniMAP) 43

You might also like