MATLAB Handout - Feb 2018
MATLAB Handout - Feb 2018
Department Matlab
CHAPTER ONE
MATLAB BASICS
» z = sqrt(y) » p = sin(pi/2)
z= p=
2.4805 + 1.6529i 1
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.
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.6 Functions
In MATLAB you will use both built-in functions as well as functions that you create yourself.
The function log is the natural logarithm, called “ln” in many texts. Now consider
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:
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:
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.
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);
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:
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
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):
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
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.
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.
A = [1 2 1; 3 2 1; 1 1 1];
B = [A eye(3)]
C = rref(B);
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.
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).
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)
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
>> 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
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
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).
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)
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.
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:
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
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
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.
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).
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.
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)
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
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.
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);
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.
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
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.
Colors, Line Styles, and Markers: Refer to help plot Fig. 3.3 Line Style Plots of Eg. 3.2.3
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)')
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)
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
compass
feather
quiver
quiver3
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.
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.
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.
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.
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.
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
Fig. 4.7
Build the following circuit and simulate with entire input combinations
Fig. 4.8
FURTHER EXAMPLES
THERMAL MODEL OF A HOUSE
Open the sldemo_househeat model
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
REFERENCES
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