Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
45 views

MATLAB Handout - Feb 2018

This document provides an introduction to MATLAB basics, including: 1. Fundamental expressions and operations in MATLAB such as arithmetic operators and precedence rules. 2. How to build matrices using various methods such as specifying individual elements or using built-in functions like eye(), zeros(), and rand(). 3. Common matrix operations in MATLAB such as addition, transpose, and extracting sub-matrices. That's a high-level 3 sentence summary of the key information from the provided document on MATLAB basics.

Uploaded by

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

MATLAB Handout - Feb 2018

This document provides an introduction to MATLAB basics, including: 1. Fundamental expressions and operations in MATLAB such as arithmetic operators and precedence rules. 2. How to build matrices using various methods such as specifying individual elements or using built-in functions like eye(), zeros(), and rand(). 3. Common matrix operations in MATLAB such as addition, transpose, and extracting sub-matrices. That's a high-level 3 sentence summary of the key information from the provided document on MATLAB basics.

Uploaded by

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

UMaT: Electrical and Electronic Eng.

Department Matlab
CHAPTER ONE
MATLAB BASICS

1.1 Fundamental Expressions/Operations


MATLAB uses conventional decimal notion, builds expressions with the usual arithmetic operators
(help ops) and precedence rules:
» x = 3.421 » y = x+8.2i
x= y=
3.4210 3.4210 + 8.2000i

» z = sqrt(y) » p = sin(pi/2)
z= p=
2.4805 + 1.6529i 1

1.2 Building Matrix

Matrix A can be equivalently introduced in the following ways.

(a) >> A = [1 2 3 ; 4 4 3 ; 2 2 4] (b) >> A = [1 2 3 (c) >> A = [1, 2, 3; 4 4 3


443 2 2 4]
2 2 4]
In all three cases MATLAB, will reply with A=
1 2 3
4 4 3
2 2 4

Let A be an m by n matrix. The size of A can be determined in several ways:


[m , n]=size(A)
m=size(A,1)
n=size(A,2)
The entry in the ith row and the jth column can be accessed by A (i , j)

If A and B are the same size, then A.*B is the element-by-element product of A and B.
Likewise, A./B is the element-by-element quotient of A and B, and A.c is the matrix formed by raising
each of the elements of A to the power c. More generally, if f is one of the built-in functions in MATLAB,
or is a user-defined function that accepts vector arguments, then f(A) is the matrix obtained by applying
f element-by-element to A. See what happens when you type sqrt(A), where A is the matrix defined as
x(3) third element of vector x.

Compiled by: J. K. Annan 1


UMaT: Electrical and Electronic Eng. Department Matlab
Convenient matrix building functions are
eye identity matrix
zeros matrix of zeros
ones matrix of ones
diag diagonal matrix
triu upper triangular part of a matrix
tril lower triangular part of a matrix
rand randomly generated matrix
For example,
»A = eye(3) » B = zeros(3,2) » C = rand(3,1)
A= B= C=
100 0 0 0.9501
010 0 0 0.2311
001 0 0 0.6068
Matrices can be built from blocks. For example,
» D = [A B C]
D=
1.0000 0 0 0 0 0.9501
0 1.0000 0 0 0 0.2311
0 0 1.0000 0 0 0.6068

1.3 Matrix Operations


Matrix operations are fundamental to MATLAB. Within a matrix, columns are separated
by space, and the rows are separated by semicolon”;”. For example
4
» A = [1 2 3; 4 5 6; 7 8 9]
A=
1 2 3
4 5 6
7 8 9
» A = [1,2,3; 4,5,6;7,8,9]
A=
1 2 3
4 5 6
7 8 9
» B = ones(3,3)
B=
111
111
111
» A+B
ans =
234
567
8 9 10
» A'
ans =
147
258
369
Compiled by: J. K. Annan 2
UMaT: Electrical and Electronic Eng. Department Matlab
Other Matrix Operations
 magic(n): produces a magic square of dimension n
 pascal(n): produces a Pascal triangle of dimension n
 diag: extracts a diagonal
 fliplr: flips from left to right
 flipud: flips from top to bottom
 rot90: rotate the matrix 90 degrees

1.4 Retrieving part or an element of a matrix


» D(:,6) » D (1, :) » D (1,6)
ans = ans = ans =
0.9501 1.0000 0 0 0 0 0.9501 0.9501
0.2311
0.6068

A(2,3) Represents the 2, 3 element of A, i.e., element in the second row and third column.
A(2,[2 4]) Yields the second and fourth elements of the second row of A.
A(2,2:4) Select the second, third, and fourth elements of this row, type.
A(2:3,2:4) Sub-matrix consisting of elements in rows 2 and 3 and in columns 2, 3, and 4
A(:,2) Denotes the second column of A, and
A(3,:) Yields the third row of A.

1.5 Arrays (or Vectors)


Set up a vector x which contains the values from zero to one in steps of one tenth. This can be done in
a variety of ways:
% List all the values
x = [0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.0];
% Use the colon construction
x = 0:0.1:1.0;
% Or use the command linspace
x = linspace(0,1,11);
Array Extraction Procedures
Some ways of extracting arrays include:
x = linspace(0,1,10);
y = x(1:end); % Whole of x
y = x(1:end/2); % First half
y = x(2:2:end); % Even indices only
y = x(2:end-1); % All but the last one

1.6 Functions
In MATLAB you will use both built-in functions as well as functions that you create yourself.

1.6.1 Built-in Functions


MATLAB has many built-in functions. These include sqrt, cos, sin, tan, log, exp, and atan (for
arctan) as well as more specialized mathematical functions suchas gamma, erf, and besselj. MATLAB

Compiled by: J. K. Annan 3


UMaT: Electrical and Electronic Eng. Department Matlab
also has several built-in constants, including pi (the number π), i (the complex number i = √−1), and
Inf (∞). Here are some examples:

>> log(exp(3)) ans = 3

The function log is the natural logarithm, called “ln” in many texts. Now consider

>> sin(2*pi/3) ans = 0.8660

To get an exact answer, you need to use a symbolic argument:

>> sin(sym(’2*pi/3’)) ans = 1/2*3^(1/2)

1.6.2 User-Defined Functions


In this section we will show how to use inline to define your own functions. Here’s how to define the
polynomial function f (x) = x2 + x + 1:

>> f = inline(’xˆ2 + x + 1’, ’x’)


f=
Inline function:
f(x) = x^2 + x + 1

The first argument to inline is a string containing the expression defining the function. The second
argument is a string specifying the independent variable. The second argument to inline can be
omitted, in which case MATLAB will “guess” what it should be, using the rules about “Default
Variables”. Once the function is defined, you can evaluate it:

>> f(4) ans = 21

MATLAB functions can operate on vectors as well as scalars. To make an inline function that can act
on vectors, we use MATLAB’s vectorize function. Here is the vectorized version of f (x) = x2 + x + 1:
>> f1 = inline(vectorize(’xˆ2 + x + 1’), ’x’)
f1 =
Inline function:
f1(x) = x.^2 + x + 1

Note that ^ has been replaced by .^. Now you can evaluate f1 on a vector:
>> f1(1:5) ans = 3 7 13 21 31

You can plot f1, using MATLAB graphics, in several ways that we will explore in the next section. We
conclude this section by remarking that one can also define functions of two or more variables:

>> g = inline(’uˆ2 + vˆ2’, ’u’, ’v’)


g=
Inline function:
g(u,v) = u^2+v^2

Example 1.5.1 Construct the polynomial y = (x+2)2(x3 +1) for values of x from minus one to one in
steps of 0.1.

Compiled by: J. K. Annan 4


UMaT: Electrical and Electronic Eng. Department Matlab
Here it would be laborious to type out all the elements of the vector so instead we use the colon
construction. We shall also define f = (x+2) and g = x3+1, so that we have the code:

x = -1:0.1:1;
f = x+2;
g = x.ˆ3+1;
y = (f.ˆ2).*(g);

In the construction of g we have used the dot arithmetic to cube each element and then add one to it.
When constructing y we firstly square each element of f (with f.ˆ2) and then multiply each element of
this by the corresponding element of g.

x = 1:0.01:2;
f = x.ˆ2;
g = x.ˆ3+1;
y = f./g;

(We could have combined the last three lines into the single expression y =x.ˆ2./(x.ˆ3+1);).

For the moment it may be a good idea to use intermediate functions when constructing complicated
functions.

Example 1.5.2 Construct the function y(x) = sin (x cos x / x2 + 3x + 1), for values of x from one to three
in steps of 0.02. Here, again, we use the idea of intermediate functions

x = 1:0.02:3;
f = x.*cos(x);
g = x.ˆ2+3*x+1;
y = sin(f./g);

1.6.3 Polynomial Functions


conv  Convolution and polynomial multiplication
deconv  Deconvolution and polynomial division
poly  Polynomial with speci_ed roots
polyder  Polynomial derivative
poly_t  Polynomial curve _tting
polyint  Analytic polynomial integration
polyval  Polynomial evaluation
polyvalm  Matrix polynomial evaluation
roots  Polynomial roots

Example 1.5.3 Evaluate the cubic y = x3 + 3x2 − x − 1 at the points x = (1, 2, 3, 4, 5, 6). We provide
the solution to this example as a commented code:

% Firstly set up the points at which the polynomial


% is to be evaluated
x = 1:6;
% Enter the coefficients of the cubic (note that
% these are entered starting with the
% coefficient of the highest power first

Compiled by: J. K. Annan 5


UMaT: Electrical and Electronic Eng. Department Matlab
c = [1 3 -1 -1];
% Now perform the evaluation using polyval
y = polyval(c,x)

Note that in this short piece of code everything after the % is treated by MATLAB as a comment and
so is ignored. It is good practice to provide brief, but meaningful, comments at important points within
your code.

Example 1.5.4 Plot the polynomial y = x4+x2−1 between x = −2 and x = 2 (using fifty points).

Example 1.5.5 Find the roots of the polynomial y = x3 − 3x2 + 2x using the command roots.

c = [1 -3 2 0];
r = roots(c)
This returns the answers as zero, two and one.

1.6.4 Substitution
One can substitute numerical values directly into an expression with subs. For example,

>> syms a x y;
>> a = xˆ2 + yˆ2;
>> subs(a, x, 2) ans = 4+y^2
>> subs(a, [x y], [3 4]) ans = 25

1.7 Differentiation
You can use diff to differentiate symbolic expressions, and also to approximate the derivative of a
function given numerically:
>> syms x; diff(xˆ3)
ans = 3*x^2

Alternatively,
>> f = inline(’xˆ3’, ’x’); diff(f(x))
ans = 3*x^2

The syntax for second derivatives is diff(f(x), 2), and for nth derivatives, diff(f(x), n). The command
diff can also compute partial derivatives of expressions involving several variables, as in diff(xˆ2*y,
y), but to do multiple partials with respect to mixed variables you must use diff repeatedly, as in
diff(diff(sin(x*y/z), x), y). (Remember to declare y and z symbolic.)

There is one instance where differentiation must be represented by the letter D, namely when you need
to specify a differential equation as input to a command. For example, to use the symbolic ODE solver
on the differential equation xy + 1 = y, you enter dsolve(’x*Dy + 1 = y’, ’x’)

1.8 Integration
MATLAB can compute definite and indefinite integrals. Here is an indefinite integral:
>> int (’xˆ2’, ’x’)
ans = 1/3*x^3

Compiled by: J. K. Annan 6


UMaT: Electrical and Electronic Eng. Department Matlab
As with diff, you can declare x to be symbolic and dispense with the character string quotes. Note that
MATLAB does not include a constant of integration; the output is a single anti-derivative of the
integrand. Now here is a definite integral:
>> syms x; int(asin(x), 0, 1)
ans = 1/2*pi-1

You are undoubtedly aware that not every function that appears in calculus can be symbolically
integrated, and so numerical integration is sometimes necessary. MATLAB has three commands for
numerical integration of a function f (x):

quad, quad8, and quadl

It is recommend that quadl, with quad8 as a second choice. Here’s an example:

>> syms x; int(exp(-xˆ4), 0, 1)

Warning: Explicit integral could not be found.

1.9 Limits
You can use limit to compute right- and left-handed limits and limits at infinity. For example, here is
lim as x→0 of sin(x)/x:
>> syms x;
ans = 1

To compute one-sided limits, use the ’right’ and ’left’ options. For example,
>> ans = -1
Limits at infinity can be computed using the symbol Inf:
>>
ans = 1/3

1.10 Solving System of Equations

For example, suppose we wish to solve the system


3x1 + x2 - 5x3 = 0 red - delete
x1 - 5x2 + x3 = 2 green = add
x1 + x2- 5x3 = -1
we type in is the following.
>> [x1 x2 x3] = solve ('3*x1+x2-5*x3==0','x1-5*x2+x3==2','x1+x2-5*x3==-1')

The commands sym and syms are closely related. In fact, syms x is equivalent to x = sym(’x’). The
command syms has a lasting effect on its argument (it declares it to be symbolic from now on), while
sym has only a temporary effect unless you assign the output to a variable, as in x = sym(’x’). Here is
how to add 1/2 and 1/3 symbolically:
>> sym(’1/2’) + sym(’1/3’) ans = 5/6

Finally, you can also do variable-precision arithmetic with vpa. For example, to print 50 digits of
√2,
type:
>> vpa(’sqrt(2)’, 50)
ans = 1.4142135623730950488016887242096980785696718753769
Compiled by: J. K. Annan 7
UMaT: Electrical and Electronic Eng. Department Matlab

You can type whos to see a summary of the names and types of your currently defined variables.
The “Bytes” column shows how much computer memory is allocated to each variable. Try assigning u
= pi, v = ’pi’, and w = sym(’pi’), and then type whos to see how the different data types are described.

Elementary Matrix Functions


norm(A)  The norm of A
rank(A)  The dimension of the row space of A
det(A)  The determinant of A
trace(A)  The sum of the diagonal elements of A
diag(A)  Diagonal of A
tril(A)  Lower triangular part of A
triu(A)  Upper triangular part of A
null(A)  The nullspace of A
rref(A)  Reduced Row Echelon Form of A
[l,u]=lu(A)  LU factorization triangular matrices
inv(A)  The inverse of A
[v,d]=eig(A)  v: eigenvectors, d: eigenvalues of A
poly(A)  p(  ) = det(A -  I): characteristic polynomial of A

Elementary Row Operations

There is a MATLAB command which will run through these operations, rref or in slow motion
rrefmovie. This also includes pivoting, which is how this technique deals with zeros when it
encounters them.

Example 2.8 Construct the inverse of the matrix using MATLAB.

This can be done by using the code:

A = [1 2 1; 3 2 1; 1 1 1];
B = [A eye(3)]
C = rref(B);

Compiled by: J. K. Annan 8


UMaT: Electrical and Electronic Eng. Department Matlab
CHAPTER TWO
SCRIPT WRITING

2.1 Introduction
A script is a file containing the sequence of MATLAB commands which we wish to execute to solve the
task at hand; in other words, a script is a computer program written in the language of MATLAB.

2.2 Steps in Script Writing


Script writing or programming involves setting up codes to implement an activity or event. It consists of
inputs, a set of commands and outputs.
• Inputs
o Could be initialized, defined, requested, or assigned numerical values.
Some options:
o Assign values to variables in a command line using the equal ( = ) sign.
o Use the input function for interactive assignment of values to some of the variables within
your computer program.
General format for number input:
variable = input ('Please enter a value: ')
The display in the Command window reads; Please enter a value:
Type a value after the displayed prompt; the variable will then be assigned the value that was entered.
General format for text input:
string = input ('Please enter your name: ', 's')
The display in the Command window reads: Please enter your name:
This is used when the input is a string (e.g., names, months, etc.). The variable, in this case, is a ‘char’
class (or type).
• Set of commands
o Operations applied to input variables that lead to the desired result.
• Output
o Display (graphically or numerically) result

2.2.1 Output format


All computations in MATLAB are done in double precision. The command format can be used to
change the output display format for the most convenient at the moment.
format Default. Same as short
format short Scaled fixed point format with 5 digits.
format long Scaled fixed point format with 15 digits.
format short e Floating point format with 5 digits.
format long e Floating point format with 15 digits.
Compiled by: J. K. Annan 9
UMaT: Electrical and Electronic Eng. Department Matlab
format short g Best of fixed or floating point format with 5 digits.
format long g Best of fixed or floating point format with 15 digits.
format hex Hexadecimal format.
format + The symbols +, - and blank are printed for positive, negative and zero
elements. Imaginary parts are ignored.
format bank Fixed format for dollars and cents.
format rat Approximation by ratio of small integers.
Spacing:
format compact Suppress extra line-feeds.
format loose Puts the extra line-feeds back in.
When a format is chosen, it remains effective until changed.

The fprintf() command is one way to display the value of a variable with a label.
General format of Matlab code: fprintf('format-string', variable)

To print a variable in your display on the command window, its place must be indicted by % in the
format-string followed by the format of presentation (d, f, e, g).

2.2.2 Most commonly used placeholder


%d: integer notation
%f: fixed point (decimal) notation
%e: exponential notation
%g: whichever is shorter, %f or %e

Example 1 on fprintf:
x=500;
fprintf( ‘The value of x is %f. \n’, x) Note: \n is used to create a new line space
fprintf( ‘The value of x is \n %f. ’, x) Note: the value of x will be on a line below
Example 2 on fprintf:
smiles = 77;
fprintf( ‘John smiles %d times a day. ’, smiles)
Example 3 on fprintf:
month = input( ‘Please enter your month of birth (i.e. Jan, etc): ‘, ‘s’);
day = input( ‘Please enter in number your day of birth: ‘);
fprintf( ‘Your birthday is %s %d !!’, month, day)

Compiled by: J. K. Annan 10


UMaT: Electrical and Electronic Eng. Department Matlab
2.2.3 Width & precision fields
o The width field specifies the minimum number of characters to be printed.
o The precision field specifies number of those characters that will show up after the decimal point.
Example on width and precision:
weight = 23476.54;
fprintf( ‘The weight is %8.2f pounds \n’ , weight)
fprintf( ‘The weight is %50.2f pounds \n’ , weight)

2.3 Programming
Programme 1: Write a computer program to compute the roots of the following equation:
a .* x.^2 + b .* x + c = 0
Develop the structure plan, e.g.:
1. Start (summary of Fig. 3.3 in the text)
2. Input data (a, b, c)
3. If a = 0, b = 0, and c = 0, indeterminate.
4. If a = b = 0, no solution.
5. If a = 0, x = -c/b; one root; equation is linear.
6. If b^2 < 4ac, roots are complex.
7. If b^2 = 4ac, roots are equal, x = b/(2a).
8. If b^2 > 4ac, then the roots are:
x1 = (-b + sqrt( b.^2 – 4.*a.*c)./(2.*a)
x2 = (-b - sqrt( b.^2 – 4.*a.*c)./(2.*a)
Stop

Translate this plan to a program:


%Comprehensive programme to compute roots of quadratic equation
% START OF CODE
% Quadratic equation roots based on the theoretical formula for the roots.
% a .* x.^2 + b .* x + c = 0
% Step 1: Start
clear; clc
format compact
disp(' ')
disp(' Quadratic roots finder ')
disp(' ')

Compiled by: J. K. Annan 11


UMaT: Electrical and Electronic Eng. Department Matlab
% Step 2: Input data
A = input(' Specify coefficients as follows: [a, b, c] = ');
a = A(1);
b = A(2);
c = A(3);
% Step 3: Evaluation of roots
if a==0 & b==0 & c==0
disp(' Solution is indeterminate ')
elseif a==0 & b==0
disp(' There is no solution ')
elseif a==0
x = -c/b
x1 = x; x2=x;
disp(' Only one root: equation is linear.')
elseif b.^2 < 4.*a.*c
x1 = (-b + sqrt(b.^2-4.*a.*c) )./(2.*a)
x2 = (-b - sqrt(b.^2-4.*a.*c) )./(2.*a)
disp(' Complex roots')
elseif b.^2 == 4.*a.*c
x = -b./(2.*a)
x1=x;x2=x;
disp(' Equal roots')
else % b.^2 > 4.*a.*c
x1 = (-b + sqrt(b.^2-4.*a.*c) )./(2.*a);
x2 = (-b - sqrt(b.^2-4.*a.*c) )./(2.*a);
disp(' x1,x2 the two distinct roots')
disp([x1 x2])
end
format
disp('check')
coef = [a b c];
roots_of_quad = polyval(coef,[x1,x2])
%

Compiled by: J. K. Annan 12


UMaT: Electrical and Electronic Eng. Department Matlab

Programme 2: Temperature conversion problem: Convert C to F or F to C.


%
% Temperature conversion from C to F
% or F to C as requested by the user
%
Dec = input(' Which way?: 1 => C to F? 0 => F to C: ');
Temp = input(' What is the temperature you want to convert? ');
%
% Note the logical equals sgn (==)
if Dec == 1
TF = (9/5)*Temp + 32;
disp(' Temperature in F: ')
disp(TF)
else
TC = (5/9)*(Temp-32);
disp(' Temperature in C: ')
disp(TC)
end

Programme 3: Repetition: X and Y coordinate for a Particular Hyperbolic Tangent


%
% Ski slope offsets for the
% HYPERBOLIC TANGENT DESIGN
%
% Points at which the function
% is to be evaluated:
% Step 1: Input x
x = -5:0.5:5;
% Step 2: Compute the y offset,
% that is, the altitude:
y = 1 - tanh(3.*x./5);
%
% Step 3: Display results in a table
%

Compiled by: J. K. Annan 13


UMaT: Electrical and Electronic Eng. Department Matlab
disp(' ') % Skips a line
disp(' X Y')
disp([x' y'])

2.4 Function: M-files


The first line of a function m-file has the form:
function [outArgs] = funName(inArgs)
outArgs are enclosed in [ ]
• outArgs is a comma-separated list of variable names
• [ ] is optional if there is only one parameter
• functions with no outArgs are legal
inArgs are enclosed in ( )
• inArgs is a comma-separated list of variable names
• functions with no inArgs are legal

>> twosum(2,2)
ans =
4
>> x = [1 2]; y = [3 4];
>> twosum(x,y)
ans =
46
>> A = [1 2; 3 4]; B = [5 6; 7 8];
>> twosum(A,B);
ans =
6 8
10 12

Example
function [output] = xsq(input)
output = input.ˆ2;
The first line of xsq.m tells us that this is a function called xsq which takes an input called input and
returns a value called output. NB: The input is contained in round brackets, whereas the output is
contained within square brackets. Execution of function is demonstrated as:
>> A = [1 2 3 4 5 6];
Compiled by: J. K. Annan 14
UMaT: Electrical and Electronic Eng. Department Matlab
>> y = xsq(A)
y=
1 4 9 16 25 36

2.4.1 Multiple Input Multiple Output Functions


Example 2.4.1: Suppose we want to plot contours of a function of two variables z = x2 + y2.
function [output] = func(x,y)
output = x.ˆ2 + y.ˆ2;
which should be saved in the file func.m. The first line indicates that this is a function which has two
inputs x and y, and returns a single output output. The next line calculates the function x2 + y2.

Plotting contours with coded function of example 2.4.1;


x = 0.0:pi/10:pi;
y = x;
[X,Y] = meshgrid(x,y);
f = func(X,Y);
contour(X,Y,f)
axis([0 pi 0 pi])
axis equal

Example 2.4.2: Suppose we now want to construct the squares and cubes of the elements of a vector.
We can use the code
function [sq,cub] = xpowers(input)
sq = input.ˆ2;
cub = input.ˆ3;
This function file could be saved as xpowers.m and it can be called as follows:
x = 1:10;
[xsq,xcub] = xpowers(x);
This gives
>> xsq
xsq =
1 4 9 16 25 36 49 64 81 100
>> xcub
xcub =
1 8 27 64 125 216 343 512 729 1000

Compiled by: J. K. Annan 15


UMaT: Electrical and Electronic Eng. Department Matlab
Example 2.4.3: As you might expect a function can have multiple inputs and outputs:
function [out1,out2] = multi(in1,in2,in3)
out1 = in1 + max(in2,in3);
out2 = (in1 + in2 + in3)/3;
which should be saved as multi.m.
We can call this function in the following way
x1 = 2; x2 = 3; x3 = 5;
[y1,y2] = multi(x1,x2,x3);
y1, y2
For this example, we obtain y1=7 and y2=3.3333.

2.5 Evaluating Polynomials and Plotting Curves


In general suppose we have the general quadratic y = a2x2 + a1x + a0. Firstly we need to define the
quadratic and this is done by fixing the three coefficients a0, a1 and a2. This can be done using the
following script, which we will call quadratic.m
% quadratic.m
% This program evaluates a quadratic
% at a certain value of x
% The coefficients are stored in a2, a1 and a0.
% SRO & JPD
%
str = ’Please enter the ’;
a2 = input([str ’coefficient of x squared: ’]);
a1 = input([str ’coefficient of x: ’]);
a0 = input([str ’constant term: ’]);
x = input([str ’value of x: ’]);
y = a2*x*x+a1*x+a0;
% Now display the result
disp([’Polynomial value is: ’ num2str(y)])

2.6 Functions of Functions


Given the function;
h(x) = 2sin2 x + 3sinx − 1.
One way of writing code that would evaluate this function is
function [h] = fnc(x)
h = 2*sin(x).*sin(x)+3*sin(x)-1
Compiled by: J. K. Annan 16
UMaT: Electrical and Electronic Eng. Department Matlab
However we can recognise this function as a composition of two functions g(x) = sin(x) and f(x) = 2x2
+ 3x − 1 so that h(x) = f(g(x)). We can easily write a function file f.m to evaluate f(x)
function [y] = f(x)
y = 2*x.ˆ2+3*x-1;
To use this in calculating the value of the composite function h(x), we need to be able to pass the
function name to f as an argument. We can do this with the following modification to our code
function [y] = f(fname,x)
z = feval(fname,x);
y = 2*z.ˆ2+3*z-1;
Calculating the function h(x) is now as simple as
x = -pi:pi/20:pi;
y = f(’sin’,x);
plot(x,y)

2.7 Loops and Conditional Statements


Let us consider how MATLAB can be used to repeat an operation many times and how decisions are
taken.
• Loop Structures
The basic MATLAB loop command is for and it uses the idea of repeating an operation for all the
elements of a vector. The syntax associated with the for command is:
for ii = 1:N
commands
end
A simple example helps to illustrate this:
% looping.m
%
N = 5;
for ii = 1:N
disp([int2str(ii) ’ squared equals ’ int2str(iiˆ2)])
end
This gives the output
1 squared equals 1
2 squared equals 4
3 squared equals 9
4 squared equals 16
5 squared equals 25

Compiled by: J. K. Annan 17


UMaT: Electrical and Electronic Eng. Department Matlab

Example 2.7.1: The following code writes out the seven times table up to ten seven’s.
str = ’ times seven is ’;
for j = 1:10
x=7*j;
disp([int2str(j) str int2str(x)])
end
The first line sets the variable str to be the string “ times seven is ” and this phrase will be used in
printing out the answer. In the code this character string is contained within single quotes. It also has a
space at the start and end.

Example 2.7.2: The following code prints out the value of the integers from 1 to 20 (inclusive) and
their prime factors. To calculate the prime factors of an integer we use the MATLAB command factor
for i = 1:20
disp([i factor(i)])
end

This loop runs from i equals 1 to 20 (in unit steps) and displays the integer and its prime factors. There
is no need to use int2str (or num2str) here since all of the elements of the vector are integers. The
values for which the for loop is evaluated do not need to be specified inline, instead they could be set
before the actual for statement. For example
r = 1:3:19;
for ii = r
disp(ii)
end

Example 2.7.3: Suppose we want to calculate the quantity six factorial (6! = 6 × 5 × 4 × 3 × 2 × 1)
using MATLAB. One possible way is
fact = 1;
for i = 2:6
fact = fact * i;
end
To understand this example it is helpful to unwind the loop and see what code has actually been
executed (we shall put two commands on the same line for ease)
fact = 1;
i=2; fact = fact * i; At this point fact is equal to 2
i=3; fact = fact * i; At this point fact is equal to 6
i=4; fact = fact * i; At this point fact is equal to 24
Compiled by: J. K. Annan 18
UMaT: Electrical and Electronic Eng. Department Matlab
i=5; fact = fact * i; At this point fact is equal to 120
i=6; fact = fact * i; At this point fact is equal to 720
The same calculation could be done using the MATLAB command factorial(6).

Example 2.7.4: Determine the sum of the geometric progression


This is accomplished using the code:
total = 0
for n = 1:6
total = total + 2ˆn;
end
The script above can be automated using the MATLAB code:
N = input(’Enter the number of terms required: ’);
s = 0;
for i = 1:N
s = s + iˆ2;
end
disp([’Sum of the first ’ int2str(N) ...
’ squares is ’ int2str(s)])
As was mentioned earlier the command int2str converts an integer to a string. This means we can
concatenate these strings into a sentence. If we tried
apple = 8;disp([’I have ’ apple ’ apples’])
MATLAB misses out the number and gives “I have apples”, whereas the command
disp([’I have ’ int2str(apple) ’ apples’]) gives “I have 8 apples”, as required:
maxN = input(’Enter the maximum value of N required: ’);
I(1) = 1ˆ2;
for N = 2:maxN
I(N) = I(N-1) + Nˆ2;
end
disp([’Values of I_N’])
disp([1:N; I])
This code uses a vector I to store the results of the calculation. It first prompts the user to input the
value of N, which it stores in the variable maxN. The first value of the vector is then set as 12.
Equation (3.1) now tells us the relation between the first and second elements of I, which we exploit in
the loop structure. The final two lines display the string Values of I N and the actual values. The
answers are given as a matrix, the first row of which contains the numbers 1 to N and the second row
gives the corresponding values of I_N.

Compiled by: J. K. Annan 19


UMaT: Electrical and Electronic Eng. Department Matlab

2.8 Sums of Series of the Form

Let’s consider the simple code which works out the sum of the first N integers raised to the power p:
% Summing series
N = input(’Please enter the number of terms required ’);
p = input(’Please enter the power ’);
sums = 0;
for j = 1:N
sums = sums + jˆp;
end
disp([’Sum of the first ’ int2str(N) ...
’ integers raised to the power ’ ...
int2str(p) ’ is ’ int2str(sums)])
2.9 Summing Series Using MATLAB Specific Commands
i = 1:10;
i_squared = i.ˆ2;
value = sum(i_squared)
This can all be contracted on to one line: sum((1:10).ˆ2):

Evaluate the expression for N = 10 (the symbol π means the product of the terms,
much in the same way means summation). This can be done using the code:
n = 1:10;
f = 1+(2)./n;
pr = prod(f)

2.10 Nested Loops


Many algorithms require us to use nested loops (loops within loops). This is illustrated this using a
simple example of constructing an array of numbers:
for ii = 1:3
for jj = 1:3
a(ii,jj) = ii+jj;
end
end
Notice that the inner loop (that is, the one in terms of the variable jj) is executed three times with ii equal
to 1, 2 and then 3. These structures can be extended to have further levels. Notice each for command
Compiled by: J. K. Annan 20
UMaT: Electrical and Electronic Eng. Department Matlab
must be paired within an end, and for the sake of readability these have been included at the same level
of indentation as their corresponding for statement.

Example 2.10.1 Calculate the summations for p equal to 1, 2 and 3 for N = 6.

We could perform each of these calculations separately but since they are so similar it is better to
perform them within a loop structure:
N = 6;
for p = 1:3
sums(p) = 0.0;
for j = 1:N
sums(p) = sums(p)+jˆp;
end
end
disp(sums)
The order in which the loops occur should be obvious for each problem but in many examples the
outer loop and inner loop could be reversed.

2.11 Conditional Statements


MATLAB has a very rich vocabulary when it comes to conditional operations but we shall start with
the one which is common to many programming languages (even though the syntax may vary slightly).
This is the if command which takes the form:
if (expression)
commands
...
end
As one might expect, if the expression is true then the commands are executed, otherwise the
programme continues with the next command immediately beyond the end statement. There are more
involved forms of the command; below is the construction of the expression. First, there are the simple
mathematical comparisons
a<b True if a is less than b
a <= b True if a is less than or equal to b
a>b True if a is greater than or equal to b
a >= b True if a is greater than or equal to b
a == b True if a is equal to b
a ~= b True if a is not equal to b
Often, we will need to form compound statements, comprising more than one condition. This is done by
using logical expressions, these are:
Compiled by: J. K. Annan 21
UMaT: Electrical and Electronic Eng. Department Matlab
and(a,b) a & b Logical AND
or(a,b) a|b Logical OR
not(a) ~a NOT
xor(a,b) Logical exclusive OR
The effect of each of these commands is perhaps best illustrated by using tables

AND false true


OR false true
false false false
false false true
true false true
true true true

XOR false true

false false true

true true false

NOT (~) This simply changes the state so ~(true) = false and ~(false) = true.
We pause and just run through these logical operators:
a AND b This is true if both a and b are true
a OR b This is true if one of a and b is true (or both).
a XOR b This is true if one of a and b is true, but not both.
In many languages you can define Boolean (named after
Example 2.11.1 Here we construct a conditional statement which evaluates the function:

One of the possible solutions to this problem is:


if x >= 0 & x <= 1
f = x;
elseif x > 1 & x <= 2
f = 2-x;
else
f = 0;
end

Compiled by: J. K. Annan 22


UMaT: Electrical and Electronic Eng. Department Matlab
Notice that it has not been necessary to treat the end conditions separately; they are both included in
the final else clause.

Example 2.11.2 (Nested if statements) The ideas behind nested if statement is made clear by the
following example
if raining
if money_available > 20
party
elseif money_available > 10
cinema
else
comedy_night_on_telly
end
else
if temperature > 70 & money_available> 40
beach_bbq
elseif temperature>70
beach
else
you_must_be_in_the_UK
end
end

2.12 The MATLAB Command ‘Switch’


MATLAB has a command called switch which is similar to the BASIC command select (the syntax is
virtually identical). The command takes the form:
switch switch_expr
case case_expr1
commands ...
case {case_expr2,case_expr3}
commands ...
otherwise
commands ...
end

Let’s consider a typical application for this command:


Compiled by: J. K. Annan 23
UMaT: Electrical and Electronic Eng. Department Matlab
switch lower(METHOD)
case {’linear’,’bilinear’}
disp(’Method is linear’)
case ’cubic’
disp(’Method is cubic’)
case ’nearest’
disp(’Method is nearest’)
otherwise
disp(’Unknown method.’)
end

This code assumes that METHOD has been set as a string. The first command lower(METHOD)
changes the string to be lower case (there is also the corresponding command upper). This value is then
compared to each case in turn and if no matches are found the otherwise code is executed.

Example 2.12.1 We refer to the old rhyme that allows us to remember the number of days in a month.
Thirty days hath September
April, June and November
All the rest have thirty-one
Except February alone
which has twenty-eight days clear
and twenty-nine on leap year

This rhyme is exploited in the code:


msg = ’Enter first three letters of the month: ’;
month = input(msg,’s’);
month = month(1:3); % Just use the first three letters
if lower(month)==’feb’
leap = input(’Is it a leap year (y/n): ’,’s’);
end
switch lower(month)
case {’sep’,’apr’,’jun’,’nov’}
days = 30;
case ’feb’
switch lower(leap)
case ’y’
Compiled by: J. K. Annan 24
UMaT: Electrical and Electronic Eng. Department Matlab
days = 29;
otherwise
days = 28;
end
otherwise
days = 31;
end

The MATLAB command lower forces the characters in the string to be lower case: for instance if the
user typed ’Feb’ the command lower would return ’feb’. We have also included a command which makes
sure the code only considers the first three characters of what the user inputs. The command input is
used here with a second argument ’s’ which tells MATLAB that a string is expected as an input; without
this the user would need to add single quotes at the start and end of the string.

2.13 Conditional loops


Suppose we now want to repeat a loop until a certain condition is satisfied. This is achieved by making
use of the MATLAB command while, which has the syntax
while (condition)
commands...
end

This translates into English as: while condition holds continue executing the commands.... Below are a
couple of simple examples.

Example 2.13.1 Write out the values of x2 for all positive integer values x such that x3 < 2000. To do
this we will use the code
x = 1;
while xˆ3 < 2000
disp(xˆ2)
x = x+1;
end
value = floor((2000)ˆ(1/3))ˆ2;

This first sets the variable x to be the smallest positive integer (that is one) and then checks whether x3
< 2000 (which it is). Since the condition is satisfied it executes the command within the loop that it
displays the values of x2 and then increases the value of x by one. The final line uses some mathematics
to check the answer, with the MATLAB command floor (which gives the integer obtained by rounding
down; recall the corresponding command to find the integer obtained by rounding up is ceil).

Compiled by: J. K. Annan 25


UMaT: Electrical and Electronic Eng. Department Matlab

2.14 The Break Command


A command which is of great importance within the context of loops and conditional statements is the
break command. This allows loops to stop when certain conditions are met. For instance, consider the
loop structure
x = 1;
while 1 == 1
x = x+1;
if x > 10
break
end
end

The loop structure while 1==1 ... end is very dangerous since this can give rise to an infinite loop, which
will continue ad infinitum. However, the break command allows control to jump out of the loop.

2.15 Error Command


Example 2.15.1: Write a code which asks the user for an integer and returns the prime factors of that
integer.
msg = ’Please enter a strictly positive integer: ’;
msg0 = ’You entered zero’;
msg1 = ’You failed to enter an integer’;
msg2 = ’You entered a negative integer’;
x = input(msg);
if x==0
error(msg0)
end
if round(x)˜= x
error(msg1)
end
if sign(x)==-1
warning(msg2)
x = -x;
end
disp(factor(x))

Compiled by: J. K. Annan 26


UMaT: Electrical and Electronic Eng. Department Matlab
Fortunately the command input has its own error checking routine and will only let you input numbers
(if you try inputting a string it will complain). We now check to see whether zero is entered, in which
case the code stops after having informed the user that they entered a zero. Similarly, if the user enters
a non integer the code will stop. If the user enters a negative integer the code warns the user they have
done so but simply makes it equal to the corresponding positive value.

2.16 Roots of a Polynomial


MATLAB has a specific command for finding the roots of a polynomial, namely roots. The
coefficients of the polynomial are placed in a vector c and the routine returns the corresponding roots.
It is very simple to use, but care is needed when entering the coefficients.

Example 2.16.1: Find the roots of the quintic equation f(x) = x5 − x4 + x3 + 2x2 − 1. This is
accomplished using the code:
c = [1 -1 1 2 0 -1];
roots(c)

There are a couple of things to note from this example:


– The polynomial’s coefficients are listed starting with the one corresponding to the largest power.
– It is crucial that zeros are included in the sequence where necessary (in the above we have included
the zero times x term).
– As a simple check, a polynomial of order p has p + 1 coefficients, i.e. a quadratic has three
coefficients and a polynomial of degree p will have p roots. So as long as the coefficients of the
polynomial are real, the roots will be real or occur in complex conjugate pairs.

2.17 Saving and Reading Data


To save all the variables which are currently in use:
% Save all current variables in a file
% session_vars.mat
save session_vars
This creates a file called session vars.mat, where the first part of this filename is user-defined to reflect
the contents of the file and the second part .mat defines it as a MATLAB file containing variables.
Note this suffix may also be used by another package and as such it will be difficult to use the Open
menu. This file now contains the actual variables, which means both their names and values are stored.
They can be reloaded using the command:
% Loads the variables stored in the
% file session_vars.mat
load session_vars

If we wish to save only certain variables we can list them:

Compiled by: J. K. Annan 27


UMaT: Electrical and Electronic Eng. Department Matlab
% Save the variables a & a1 to the
% file session_vars.mat
save session_vars a a1
% Save all variables starting with b
% to session_vars.mat
save session_vars b*
% Append all variables starting with ca
% to the file session_vars.mat
save session_vars ca* -append
This last command is particularly useful since it adds the variables to the file whereas the previous
ones erase all the other variables currently stored in the files. If we merely want to save the data from
variables (rather than their names) we can again use save but with a different syntax. This time we
shall specify the entire filename, which needs to be enclosed within single quotes.
save ’session_vals.dat’ a a1 -ascii
This produces an ASCII (American Standard Code for Information Interchange – basically human
readable) file containing the values of the variables a and a1.

Diary: Records the user commands and output. This is useful to see which commands have been used.
One can specify the file in which the output is stored:
diary(’list.diary’)
x = 1:10;
y = x.ˆ2;
diary off

Consider a file containing the data


1.0000000e+000 2.0000000e+000 3.0000000e+000 4.0000000e+000
1.0000000e+000 4.0000000e+000 9.0000000e+000 1.6000000e+001
(this was created using the code: x = 1:4; y = x.ˆ2; save ’king.dat’ x y -ascii). This contains two rows
vectors and we can load this using:
load ‘king.dat’
Now using the command whos we can see that we have a two-by-four array called king. We can now
extract the data using
a = king(1,:);
b = king(2,:);
clear king.
These commands give us the first row and the second row in the row vectors a and b; finally we clear
the array king since we have extracted the requisite data.

Compiled by: J. K. Annan 28


UMaT: Electrical and Electronic Eng. Department Matlab
Consider this code
x = 0:.4:2;
y = [x; exp(x).*cos(2*x)];
fid = fopen(’data.dat’,’w’);
fprintf(fid,’%6.2f %12.8f\n’,y);
fclose(fid);

In the first two lines we set up a vector x running from 0 to 2 in steps of 0.4 and then a matrix y comprising
two columns (first x and then the corresponding values of the function ex cos 2x). The next line opens a
file data.dat using the command fopen (note the fact that the filename must be enclosed in single quotes).
The first argument is the filename and the second one reflects what we are going to do: in this case write
to the file. The options for this second argument are:
’r’ read
’w’ write (create if necessary)
’a’ append (create if necessary)
’r+’ read and write (do not create)
’w+’ truncate or create for read and write
’a+’ read and append (create if necessary)
’W’ write without automatic flushing
’A’ append without automatic flushing
This list can be obtained by typing help fopen.

The other option of the most use is e, so the line would be changed to: _
fprintf(fid,’%6.2e %12.8e \n’,y)

which produces floating point versions of the above. The command \n gives a new line after printing
the two numbers, whilst we could place a tab between the characters using \t. Finally we use the
command fclose(fid) to close the file corresponding to the the file identifier fid. It is very good practice
to close the files we are using as soon as we have finished with them.

2.18 Integrating Using MATLAB Commands


As with many examples in this text we can also use standard MATLAB commands, for instance quad
and quad8 (see help quad).

QUAD Numerically evaluate integral, adaptive Simpson quadrature.


Q = QUAD(FUN,A,B) tries to approximate the integral of function FUN from A to B to within an
error of 1.e-6 using recursive adaptive Simpson quadrature. The function Y = FUN(X) should accept a
vector argument X and return a vector result Y, the integrand evaluated at each element of X.

Compiled by: J. K. Annan 29


UMaT: Electrical and Electronic Eng. Department Matlab

Q = QUAD(FUN,A,B,TOL) uses an absolute error tolerance of TOL instead of the default, which is
1.e-6. Larger values of TOL result in fewer function evaluations and faster computation, but less
accurate results. The QUAD function in MATLAB 5.3 used a less reliable algorithm and a default
tolerance of 1.e-3. Function QUADL may be more efficient with high accuracies and smooth
integrands.

Example:
FUN can be specified in three different ways. A string expression involving a single variable:
Q = quad('1./(x.^3-2*x-5)',0,2);

An inline object:
F = inline('1./(x.^3-2*x-5)');
Q = quad(F,0,2);

A function handle:
Q = quad(@myfun,0,2);
where myfun.m is an M-file:
function y = myfun(x)
y = 1./(x.^3-2*x-5);

DBLQUAD Numerically evaluate double integral.


DBLQUAD(FUN,XMIN,XMAX,YMIN,YMAX) evaluates the double integral of FUN(X,Y) over the
rectangle XMIN <= X <= XMAX, YMIN <= Y <= YMAX. FUN(X,Y) should accept a vector X and a
scalar Y and return a vector of values of the integrand.

Example: Q = dblquad(inline('y*sin(x)+x*cos(y)'), pi, 2*pi, 0, pi)


Or Q = dblquad(@integrnd, pi, 2*pi, 0, pi)

where integrnd.m is an M-file:


function z = integrnd(x, y)
z = y*sin(x)+x*cos(y);

This integrates y*sin(x)+x*cos(y) over the square pi <= x <= 2*pi, 0 <= y <= pi. Note that the
integrand can be evaluated with a vector x and a scalar y.

Compiled by: J. K. Annan 30


UMaT: Electrical and Electronic Eng. Department Matlab
CHAPTER THREE
PLOTTING

3.1 Introduction
Basic plotting commands includes plot, xlabel, ylabel, title, grid, axis, stem, subplot
Type help plot to learn more on plot.
Plot(X,Y,'c+:') Figure(1) Subplot(m,n,p)
• Subplot command allows you to put multiple p=1 p=2 p=3
graphs on one figure window. subplot(2,3,1) subplot(2,3,2) subplot(2,3,3)
• Subplot(m,n,p) divides figure window into a p=4 p=5 p=6
grid of m rows and n columns where p identifies subplot(2,3,4) subplot(2,3,5) subplot(2,3,6)
the part of the window where the plot is placed.
Some functions that produce basic line plots are shown in table below.
Function Description
plot Graph 2-D data with linear scales for both axes
plot3 Graph 3-D data with linear scales for both axes
loglog Graph with logarithmic scales for both axes
semilogx Graph with a logarithmic scale for the x-axis and a linear scale for the y-axis
semilogy Graph with a logarithmic scale for the y-axis and a linear scale for the x-axis
plotyy Graph with y-tick labels on the left and right side

3.2 Creating Line Plots


plot(y)produces a linear graph of the elements of y(vector) versus index of the elements of y.
plot(x,y) produces a graph of y versus x(x and y are two vectors as arguments).

Example 3.2.1
• t = 0:pi/100:2*pi;
• y = sin(t);
• plot(t,y)
• grid on
Fig. 3.1 Line Plot of Eg. 3.2.1
MATLAB automatically selects appropriate axis ranges and tick mark locations.

Compiled by: J. K. Annan 31


UMaT: Electrical and Electronic Eng. Department Matlab
Example 3.2.2: Plotting three curves as a function of t in one call to plot using x-y pairs.
(MATLAB automatically cycles through a predefined list of colors to allow in each set of data).
• y2 = sin(t-0.25);
• y3 = sin(t-0.5);
• plot(t,y,t,y2,t,y3)

Example 3.2.3: Specifying Line Style


• t = 0:pi/100:2*pi; Fig. 3.2 Multiple Line Plots
• y = sin(t);
• y2 = sin(t-0.25);
• y3 = sin(t-0.5);
• plot(t,y,'-',t,y2,'--',t,y3,':')

Colors, Line Styles, and Markers: Refer to help plot Fig. 3.3 Line Style Plots of Eg. 3.2.3

3.2.1 Adding Plots to an Existing Graph


Plots can be added to existing graph using hold command.
Example 3.2.4: Statements first create a semilogarithmic
plot, then add a linear plot.
• semilogx(1:100,'+')
• hold on
• plot(1:3:300,1:100,'--')
• hold off
While MATLAB resets x-axis limits to accommodate new
data, it does not change scaling from logarithmic to linear. Fig. 3.4 Semilog Plots of Eg. 3.2.4

3.2.2 Plotting Only the Data Points


Plot marker at each data point without connecting with lines
using specification that does not contain line style. For
example;
• x = 0:pi/15:4*pi;
• y = exp(2*cos(x));
• plot(x,y,'r+') Fig. 3.5 Plot of Only Data Points
3.2.3 Plotting Imaginary and Complex Data
Compiled by: J. K. Annan 32
UMaT: Electrical and Electronic Eng. Department Matlab
When arguments to plot are complex (i.e., the imaginary part is nonzero), MATLAB ignores the
imaginary part except when plot is given a single complex argument. For this special case, the
command is a shortcut for a plot of the real part versus the imaginary part. Therefore,
• plot(Z)
where Z is a complex vector or matrix, is equivalent to
• plot(real(Z),imag(Z))
For example, this statement plots the distribution of the
eigenvalues of a random matrix using circular markers to
indicate the data points.

• plot(eig(randn(20,20)),'o','MarkerSize',6) Fig. 3.6 Plot of Complex Data Points

3.2.4 Plotting with Two Y-Axes


The plotyy command helps to create plots of two
data sets and use both left and right side y-axes.
• t = 0:pi/20:2*pi;
• y = exp(sin(t));
• plotyy(t,y,t,y,'plot','stem')

3.3 Bar and Area Graphs Fig. 3.7 Plotting with Two Y-Axes

Function Description
bar Displays columns of m-by-n matrix as m groups of n vertical bars
barh columns of m-by-n matrix as m groups of n horizontal bars
bar3 Displays columns of m-by-n matrix as m groups of n vertical 3-D bars
bar3h columns of m-by-n matrix as m groups of n horizontal 3-D bars
area 
• temp = [29 23 27 25 20 23 23 27];
• days = 0:5:35;
• bar(days,temp)
• xlabel('Day')
• ylabel('Temperature (^{o}C)')

Compiled by: J. K. Annan 33


UMaT: Electrical and Electronic Eng. Department Matlab
3.3.1 Grouped Bar Graph
By default, a bar graph represents each
element in a matrix as one bar.
• Y = [5 2 1;8 7 3;9 8
6;5 5 5;4 3 2];
• bar(Y)
The bars are clustered together by rows
and evenly distributed along the x-axis.
Fig. 3.8 Grouped Bar Graph

3.3.2 Detached 3-D Bars


The bar3 function, in its simplest form,
draws each element as a separate 3-D block
(detached bars), with the elements of each
column distributed along the y-axis.
• bar3(Y)
displays five groups of three bars along the y-axis. Fig. 3.9 Detached 3-D Bar Graph with Axes Labeling

Labeling the graph


• xlabel('X Axis')
• ylabel('Y Axis')
• zlabel('Z Axis')
• set(gca,'XTick',[1 2 3])

3.3.3 Grouped 3-D Bars


Cluster the bars from each row beside each
Fig. 3.10 Grouped 3-D Bar Graph
other by specifying the argument 'group'. For example,
• bar3(Y,'group')
groups the bars according to row and distributes the clusters evenly along the y-axis.

3.3.4 Stacked Bar Graphs to Show Contributing Amounts


Bar graphs can show how elements in the same row of a matrix contribute to the sum of all elements in
the row. These types of bar graphs are referred to as stacked bar graphs.

Compiled by: J. K. Annan 34


UMaT: Electrical and Electronic Eng. Department Matlab
Stacked bar graphs display one bar per row of a matrix. The bars are divided into n segments, where n is
the number of columns in the matrix. For vertical bar graphs, the height of each bar equals the sum of
the elements in the row. Each segment is equal to the value of its respective element.
• Y = [5 1 2;8 3 7;9 6 8;5 5
5;4 2 3];
• bar(Y,'stack')
• grid on
• set(gca,'Layer','top') %
display gridlines on top of
graph
Fig. 3.11 Stacked Bar Graph

3.3.5 Horizontal Bar Graphs


• barh(Y,'stack')
• grid on
• set(gca,'Layer','top') %
Display gridlines on top
of graph

Fig. 3.12 Horizontal Stacked Bar Graph


3.3.6 Area Graphs Showing Contributing Amounts
Example:
• Y = [5 1 2;8 3 7;9 6 8;5
5 5;4 2 3];
• area(Y)
The height of the area graph is the sum of
the elements in each row. Each successive
curve uses the preceding curve as its base.

Fig. 3.13 Area Graph showing Contributing Amounts


3.4 Pie Charts: pie and pie3 create 2-D and 3-D pie charts.
1. d=[9,2,15,6]; pie(d)
2. pie([2 4 3 5],{'North','South','East','West'})
3. pie([50 35 15])
3.4.1 Removing a Piece from a Pie Charts
When the sum of the elements in the first input argument is equal to or greater
than 1, pie and pie3 normalize the values. So, given a vector of elements x, each slice has an area

Compiled by: J. K. Annan 35


UMaT: Electrical and Electronic Eng. Department Matlab
of xi/sum(xi), where xi is an element of x. The normalized
value specifies the fractional part of each pie slice. When the
sum of the elements in the first input argument is less
than 1, pie and pie3 do not normalize the elements of
vector x. They draw a partial pie. For example,
• x = [.19 .22 .41];
• pie(x)
Fig. 3.14 Pie Chart with a
Piece Removed

3.5 Histograms in Cartesian Coordinate Systems


The hist function shows distribution of elements in Y as a histogram with equally spaced bins
between the minimum and maximum values in Y.
If Y is a vector and is the only argument, hist creates
up to 10 bins. For example,
• yn = randn(10000,1);
• hist(yn)
generates 10,000 random numbers and creates a
histogram with 10 bins distributed along the x-axis
between the minimum and maximum values of yn.

Fig. 3.15 Typical Histogram using HIST command


3.5.1 Histograms in Polar Coordinates
A rose plot is a histogram created in a polar coordinate system. For example, consider samples of the
wind direction taken over a 12-hour period.
• wdir = [45 90 90 45 360 335 360 270 335
270 335 335];
To display this data using the rose function, convert the data to
radians; then use the data as an argument to the rose function.
• wdir = wdir * pi/180;
• rose(wdir)

Fig. 3.16 Histogram in Polar Coordinates

Compiled by: J. K. Annan 36


UMaT: Electrical and Electronic Eng. Department Matlab
3.6 Discrete Data Graphs
Function Description

stem Displays a discrete sequence of y-data as stems from x-axis

stem3 Displays a discrete sequence of z-data as stems from xy-plane

stairs Displays a discrete sequence of y-data as steps from x-axis

3.6.1 Two-Dimensional Stem Plots


A stem plot displays data as lines (stems) terminated with a marker symbol at each data value. In a 2-D

graph, stems extend from the x-axis. For example, evaluating the function with the
values,
• alpha = .02; beta = .5; t = 0:4:200;
• y = exp(-alpha*t).*sin(beta*t);
yields a vector of discrete values for y at given values of t. A line plot shows the data points connected
with a straight line.
• plot(t,y)

Fig. 3.17 Two-Dimensional Stem Plots


A stem plot of the same function plots only discrete points on the curve.
• stem(t,y)
Customizing the Graph: For example, adding the string ':sr'
specifies a dotted line (:), a square marker (s), and a red color
(r). The 'fill' argument colors the face of the marker.
• stem(t,y,'--sr','fill')

Fig. 3.18 Stem Plot with Customised Lines and Markers

Compiled by: J. K. Annan 37


UMaT: Electrical and Electronic Eng. Department Matlab

3.6.2 Combining Stem Plots with Line Plots


Sometimes it is useful to display more than one plot simultaneously with a stem plot to show how you
arrived at a result.
• x = linspace(0,2*pi,60); % linearly spaced vector with 60 elements
• a = sin(x);
• b = cos(x);
stem_handles = stem(x,a+b); % Creates stem plot
for linear combination of two functions.
Overlaying a and b as line plots helps visualize the functions.
• hold on
• plot_handles = plot(x,a,'--r',x,b,'--
g');
• hold off
Fig. 3.19 Combined Stem and Line Plots

3.6.4 Three-Dimensional Stem Plots


Example

For example, you can use stem3 to visualize the Laplace transform basis function, , for a
particular constant value of s.
• t = 0:.1:10;% Time limits
• s = 0.1+i;% Spiral rate
• y = exp(-s*t);% Compute
decaying exponential
• stem3(real(y),imag(y),t)
• hold on
• plot3(real(y),imag(y),t,'r')
• hold off
• view(-39.5,62)
Fig. 3.20 Three-Dimensional Stem Plot

3.6.5 Stairstep Plots


Stairstep plots display data as the leading edges of a constant interval (i.e., zero-order hold state). This
type of plot holds the data at a constant y-value for all values between x(i) and x(i+1), where i is the

Compiled by: J. K. Annan 38


UMaT: Electrical and Electronic Eng. Department Matlab
index into the xdata. This type of plot is useful for drawing time-history plots of digitally sampled data
systems.
Example - Stairstep Plot of a Function
• alpha = 0.01;
• beta = 0.5;
• t = 0:10;
• f = exp(-alpha*t).*sin(beta*t);
• stairs(t,f)
• hold on
• plot(t,f,'--*')
• hold off Fig. 3.21 Stairstep Plot of a Function

3.7 Direction and Velocity Vector Graphs


Function Description

compass 

feather 

quiver 

quiver3 

3.7.1 Compass Plots


Example - Compass Plot of Wind Direction and Speed
This example shows a compass plot indicating the wind direction and strength during a 12-hour period.
Two vectors define the wind direction and strength.
• wdir = [45 90 90 45 360 335 360
270 335 270 335 335];
• knots = [6 6 8 6 3 9 6 8 9 10 14
12];
• rdir = wdir * pi/180; * Convert the
wind direction, given as angles, into radians
• [x,y] = pol2cart(rdir,knots);
*convert to Cartesian coordinates
• compass(x,y) Fig. 3.22 Typical Compass plot

Compiled by: J. K. Annan 39


UMaT: Electrical and Electronic Eng. Department Matlab

3.7.2 Feather Plots


The feather function shows vectors emanating from a straight line parallel to the x-axis. For example,
create a vector of angles from 90° to 0° and a vector the same size, with each element equal to 1.
• theta = 90:-10:0;
• r = ones(size(theta));
• [u,v] =
pol2cart(theta*pi/180,r*10);
• feather(u,v)
• axis equal

3.7.3 Plotting Complex Numbers Fig. 3.23 Typical Feather Plot


If the input argument, Z, is a matrix of complex numbers, feather interprets the real parts of Z as
the x components of the vectors and the imaginary parts as the y components of the vectors.
• t = 0:0.5:10; % Time limits
• s = 0.05+i; % Spiral rate
• Z = exp(-s*t); % Compute decaying exponential
• feather(Z)

Fig. 3.24 Typical Feather Plot of Complex Numbers

Student activity: Study into Quiver Plots and Cotour plots

Compiled by: J. K. Annan 40


UMaT: Electrical and Electronic Eng. Department Matlab
CHAPTER FOUR
SIMULINK

4.1 Introduction
Simulink is a tool for modelling, analysing and simulating physical and mathematical systems
including those with nonlinear elements and those that make use of continuous and discrete time. As
an extension of Matlab, Simulink adds many features specific to dynamic systems while retaining all
of Matlab’s general purpose functionality.

4.2 Step Response


Example 4.2.1: Find the step response of each of the transfer functions shown in the three equations
below and compare them.
T1 s   2
24.542
(1)
s  4 s  24.542

T2 s  
245.42

s  10 s 2  4s  24.542  (2)

T3 s  
73.626

s  3 s  4s  24.542
2
 (3)

Solution:
The step response, Ci(s), for the transfer function, Ti(s), can be found by multiplying the transfer function
by 1/s , a step input and using partial fraction expansion followed by the inverse Laplace transform to find
the response, ci(t). Going through the details, the following responses are obtained.


c1 t   1  1.09e 2t cos 4.532t  23.8o  (4)


c2 t   1  0.29e 10t  1.189e 2t cos 4.532t  53.34o  (5)


c3 t   1  1.14e 3t  0.707e 2t cos 4.532t  78.63o  (6)

Plotting these responses will give you the response curves showing the differences in comparison. This
plot could alternatively be obtained using matlab simulink tool where response parameters could be read
from the analysis of the plots. To do this, the simulink model of figure 4.1 is designed.

Fig. 4.1 Simulink Step Response Model


Compiled by: J. K. Annan 41
UMaT: Electrical and Electronic Eng. Department Matlab

Step = simulink  sources: (Step time  0; initial value  0; final value  1; sample time  0)
Gain = simulink  math: (Gain  24.542; multiplication  element-wise)
Transfer Fcn T1 = simulink  continuous: (num.  1; den.  [1 4 24.542])
Transfer Fcn T2a: (num.  245.42; den.  [1 10])
Transfer Fcn T2b: (num.  1; den.  [1 4 24.542])
Transfer Fcn T3a: (num.  73.626; den.  [1 3])
Transfer Fcn T3b: (num.  1; den.  [1 4 24.542])
Mux = simulink  signals & systems: (number of input  3; display option  bar)
Scope = simulink  sinks
Click simulation  simulation parameters…  under solver tab, set start time, stop time, etc.

4.3 Digital Block Diagram Reduction


Example 4.3.1:

Fig. 4.2 Logic Circuit for Implementing XOR logic

The logic circuit shown in figure 4.2 is used to implement the XOR logic gate using NAND gates. The
logic gates AND, OR, NAND, NOR, XOR, and NOT can be selected by first dragging the AND block
from Simulink’s Logic and Bit Operations Library (simulink  math  logical operator), and from
Function Block Parameters window, we can choose any of these six gates, and we can specify the
number of inputs and the icon shape (rectangular or distinctive). Display obtained from simulink 
sinks. Constant block is obtained from simulink  sources  constant.
Figure 4.3 is a Simulink model for the realization of the NAND logic circuit of figure 4.2.

Fig. 4.3 Simulink Model for Realisation of Fig. 4.2

Compiled by: J. K. Annan 42


UMaT: Electrical and Electronic Eng. Department Matlab
4.4 Input and Output Digital Waveforms

Example 4.4.1: Digital signal could be analysed and the resultant plotted for a particular waveform. A typical
example is shown in fig. 4.4. Drag and drop blocks from simulink library.
Data type conversion obtained from simulink  signals and systems  Data
type conversion. Choose Boolean from function block parameters shown
when data type conversion block is double-clicked.
Logical operator from simulink  math  logical operator; choosing XOR
from function block parameter. Scope from simulink  sinks. Double-click
on scope, click properties on graph, under general tab type 3 for number of
axes. Discrete pulse generator is obtained from simulink  sources.

Assignments on Digital Simulation

Parameters: Discrete Pulse Generator 1

Consider the circuits of Fig. 4.5, 4.6, 4.7: Model them in Matlab to
Parameters: Discrete Pulse Generator 2
obtain the outputs given by the Boolean expression.

Fig. 4.5

Compiled by: J. K. Annan 43


UMaT: Electrical and Electronic Eng. Department Matlab
Fig. 4.6

Fig. 4.7

Build the following circuit and simulate with entire input combinations

Fig. 4.8

Compiled by: J. K. Annan 44


UMaT: Electrical and Electronic Eng. Department Matlab

Fig. 4.9 Simulink Model of Fig. 4.8

Fig. 4.10 Full Adder Logic Circuit

Fig. 4.11 Full Adder with two Halves


Compiled by: J. K. Annan 45
UMaT: Electrical and Electronic Eng. Department Matlab

Fig. 4.12 Full Adder Circuit in Matlab for Fig. 4.10

Fig. 4.13 Full Adder Circuit for Fig. 4.11

Compiled by: J. K. Annan 46


UMaT: Electrical and Electronic Eng. Department Matlab

FURTHER EXAMPLES
THERMAL MODEL OF A HOUSE
Open the sldemo_househeat model

Figure 1: The House Heating Model


Model Initialization
This model calculates heating costs for a generic house. When the model is opened, it loads the
information about the house from the sldemo_househeat_data.m file. The file does the following:
Compiled by: J. K. Annan 47
UMaT: Electrical and Electronic Eng. Department Matlab
▪ Defines the house geometry (size, number of windows)
▪ Specifies the thermal properties of house materials
▪ Calculates the thermal resistance of the house
▪ Provides the heater characteristics (temperature of the hot air, flow-rate)
▪ Defines the cost of electricity (0.09$/kWhr)
▪ Specifies the initial room temperature (20 deg. Celsius = 68 deg. Fahrenheit)
▪ Note: Time is given in units of hours. Certain quantities, like air flow-rate, are expressed per
hour (not per second).
Model Components
Set Point
"Set Point" is a constant block. It specifies the temperature that must be maintained indoors. It is 70
degrees Fahrenheit by default. Temperatures are given in Fahrenheit, but then are converted to Celsius
to perform the calculations.
Thermostat
"Thermostat" is a subsystem that contains a Relay block. The thermostat allows fluctuations of 5
degrees Fahrenheit above or below the desired room temperature. If air temperature drops below 65
degrees Fahrenheit, the thermostat turns on the heater. See the thermostat subsystem below.
Open the Thermostat subsystem
Figure 2: The "Thermostat" Subsystem
Heater
"Heater" is a subsystem that has a constant air flow rate, "Mdot", which is specified in the
sldemo_househeat_data.m file. The thermostat signal turns the heater on or off. When the heater is on,
it blows hot air at temperature THeater (50 degrees Celsius = 122 degrees Fahrenheit by default) at a
constant flow rate of Mdot (1kg/sec = 3600kg/hr by default). The heat flow into the room is expressed
by the Equation 1.
Equation 1

Open the Heater subsystem


Figure 3: The Heater Subsystem
Cost Calculator
"Cost Calculator" is a Gain block. "Cost Calculator" integrates the heat flow over time and multiplies it
by the energy cost. The cost of heating is plotted in the "PlotResults" scope.
House
"House" is a subsystem that calculates room temperature variations. It takes into consideration the heat
flow from the heater and heat losses to the environment. Heat losses and the temperature time
derivative are expressed by Equation 2.
Equation 2

Open the House subsystem


Figure 4: The House Subsystem
Modeling the Environment
Compiled by: J. K. Annan 48
UMaT: Electrical and Electronic Eng. Department Matlab
We model the environment as a heat sink with infinite heat capacity and time varying temperature
Tout. The constant block "Avg Outdoor Temp" specifies the average air temperature outdoors. The
"Daily Temp Variation" Sine Wave block generates daily temperature fluctuations of outdoor
temperature. Vary these parameters and see how they affect the heating costs.
Running the Simulation and Visualizing the Results
Run the simulation and visualize the results. Open the "PlotResults" scope to visualize the results. The
heat cost and indoor versus outdoor temperatures are plotted on the scope. The temperature outdoor
varies sinusoidally, whereas the indoors temperature is maintained within 5 degrees Fahrenheit of "Set
Point". Time axis is labeled in hours.

Figure 5: Simulation results (time axis labeled in hours)


According to this model, it would cost around $30 to heat the house for two days. Try varying the
parameters and observe the system response.
Remarks
This particular model is designed to calculate the heating costs only. If the temperature of the outside
air is higher than the room temperature, the room temperature will exceed the desired "Set Point".
You can modify this model to include an air conditioner. You can implement the air conditioner as a
modified heater. To do this, add parameters like the following to sldemo_househeat_data.m.
▪ Cold air output
▪ Temperature of the stream from the air conditioner
▪ Air conditioner efficiency
You would also need to modify the thermostat to control both the air conditioner and the heater.

Compiled by: J. K. Annan 49


UMaT: Electrical and Electronic Eng. Department Matlab

VEHICLE ELECTRICAL SYSTEM


This example shows how to simulate the electrical system of a vehicle using Simulink® and
Simscape™ Power Systems™.
Contents
▪ System Components
▪ Operation of the System

Figure 1: The vehicle electrical system.


System Components
The system simulated consists of the following component parts:
A separately excited DC motor with constant field excitation. The armature is supplied from a DC
source voltage (battery nominal voltage 240V) and seeing that the field excitation, and hence current,
is kept constant the motor speed is directly proportional to the applied armature voltage. This
arrangement simulates the engine of the car, which drives the alternator (synchronous generator) via a
belt and pulley mechanism. As the driver accelerates, the engine speed changes as does the speed of
rotation of the alternator. Therefore to simulate a change in engine speed, the armature voltage of the
DC motor is changed.
The DC motor output power (product of motor torque and angular speed, w) is fed into the
synchronous machine block as an input.
The alternator is a 3 phase synchronous generator with its field current regulated to give control over
the output voltage. This is simulated by using the Simplified Synchronous Machine model.
The 3 phase AC output of the alternator is fed into the 6 pulse rectifier to give the DC voltage required
to charge the car battery and to supply the balance of the electrical system of the car.

Compiled by: J. K. Annan 50


UMaT: Electrical and Electronic Eng. Department Matlab
Operation of the System
The DC voltage must be kept constant so that the lights do not dim when other loads are switched on,
for example: the starter motor or windscreen wiper motor. Likewise, if the A/C fan motor is running
and the lights are switched on the fan motor must not slow down.
To ensure the DC voltage remains constant, even when the engine speed changes or when additional
electrical loads are switched on, it is necessary to feed back the DC bus voltage and regulate the
alternator generated AC voltage accordingly. The following events will help illustrate this operation:
▪ Speed variation: While the simulation is running, reduce the input DC battery voltage from 240
to say 150 V. When the simulation is over, display the DC bus voltage and the speed w of the
DC motor. It is seen that the speed changes, but there is no change in the DC bus voltage.
▪ Load variation: While the simulation is running, change the value of the load resistor connected
across the DC busbar. Display the DC bus voltage and current. The current changes with the
load, but the voltage remains constant (as it should).
▪ To illustrate that the voltage regulator on the alternator is operating, change the constant on the
second summer (the one with the two +ve signs) while the simulation is running. Display the
AC and DC voltages and they will show the changes.

PWM-CONTROLLED DC MOTOR
Try it in MATLAB
This model shows how to use the Controlled PWM Voltage and H-Bridge blocks to control a motor.
The DC Motor block uses manufacturer datasheet parameters, which specify the motor as delivering
10W mechanical power at 2500 rpm and no-load speed as 4000 rpm when run from a 12V DC supply.
Hence if the PWM reference voltage is set to its maximum value of +5V, then the motor should run at
4000 rpm. If it is set to +2.5V, then it should run at approximately 2000 rpm. The Simulation model
parameter is set to Averaged for both the Controlled PWM Voltage and H-Bridge blocks, resulting in
fast simulation. To validate the averaged behavior, change the Simulation mode parameter to PWM in
both blocks.
Model

Simulation Results from Simscape Logging


The plot below shows the current passing through the motor and the speed of the motor shaft.

Compiled by: J. K. Annan 51


UMaT: Electrical and Electronic Eng. Department Matlab

REFERENCES

Anon. (2012). “MATLAB”, http: //en.m.wikipedia.org/wiki. Retrieved: 14 July 2012

Ferraera, A. J. M. (2009). “MATLAB Codes for Finite Element Analysis”, Springer. ISBN: 978-1-
4020-9199-5

Gilat, A. (2004). MATLAB: An Introduction with Applications”, 2nd Edition, John Wiley & Sons.
ISBN 978-0-471-69420-5

Lynch, S. (2004). “Dynamical Systems with Applications using MATLAB”, Birkhauser. ISBN: 978-0-
8176-4321-8

Otto, S. R. and Denier, J. P. (2005). “An Introduction to Programming and Numerical Methods in
MATLAB”, Springer-Verlag Limited, London

Quarteroni, A. and Fausto, S. (2006). “Scientific Computing with MATLAB and Octave”, Springer.
ISBN: 978-3-540-32612-0

Compiled by: J. K. Annan 52

You might also like