Lab 2 SP18
Lab 2 SP18
LAB # 02
Introduction to MATLAB
1
[INTRODUCTION TO MATLAB] Signals and Systems
There are certain relational operators in MATLAB. Table 2.1 shows a list of such operators
Note that a single ‘=’ denotes assignment and never a test for equality in MATLAB.
2
[INTRODUCTION TO MATLAB] Signals and Systems
>> A <= B
ans =
1 1
0 0
For Information
To test whether arrays A and B are equal, that is, of the same size with identical elements, the expression isequal(A,B) can be
used:
>> isequal(A,B)
ans =
0
The function isequal is one of many useful logical functions whose names begin with is, a selection of which is listed in Table 2.2.
For example, isinf(A) returns a logical array of the same size as A containing true where the elements of A are plus or minus inf
and false where they are not:
The function isnan is particularly important because the test x == NaN always produces the result 0 (false), even if x is a NaN!
(A NaN is defined to compare as unequal and unordered with everything.)
>> isnan(A)
ans =
0 0
0 1
>> A == NaN
ans =
0 0
0 0
Note that an array can be real in the mathematical sense, but not real as reported by isreal. For isreal(A) is true if A has no
imaginary part. Mathematically, A is real if every component has zero imaginary part. How a mathematically real A is formed can
determine whether it has an imaginary part or not in MATLAB. The distinction can be seen as follows:
>> a = 1;
>> b = complex(1,0);
>> c = 1 + Oi;
>> [a b c]
ans =
1 1 1
>> whos a b c
Name Size Bytes Class Attributes
a 1x1 8 double
b 1x1 16 double complex
c 1x1 8 double
3
[INTRODUCTION TO MATLAB] Signals and Systems
Like the relational operators, the &, |, and ~ operators produce matrices of logical 0s and 1s when one of
the arguments is a matrix. When applied to a vector, the all function returns 1 if all the elements of the
vector are nonzero and 0 otherwise. The any function is defined in the same way, with "any" replacing
"all". Examples:
>> x = [-1 1 1] ; y = [1 2 -3] ;
>> x > 0 & y > 0
ans =
0 1 0
>> x > 0 | y > 0
ans =
1 1 1
>> xor(x > 0, y > 0)
ans =
1 0 1
>> any(x > 0)
ans =
1
4
[INTRODUCTION TO MATLAB] Signals and Systems
The second feature of these "double barreled" operators is that they short-circuit the evaluation of the
logical expressions, where possible. In the compound expression exprl && expr2, if exprl evaluates to false
then expr2 is not evaluated. Similarly, in exprl || expr2, if exprl evaluates to true then expr2 is not evaluated.
5
[INTRODUCTION TO MATLAB] Signals and Systems
method is to create a script M-file. Here, one makes a file with the same code one would enter in a terminal
window. When the file is ―run‖, the script is carried out. The third method is the function M-file. This
method actually creates a function, with inputs and outputs. The fourth method will not be discussed here.
It is a way to incorporate C code or FORTRAN code into MATLAB; this method uses .mex. We will not
discuss it here.
>> x=-pi:pi/40:pi;
>> y=x.*sin(3*x.^2).*exp(-x.^2/4);
>> plot(x,y)
The code listed above creates the row vector x, and then uses it to form a row vector y whose entries are the
𝑥2
values of the function 𝑥𝑠𝑖𝑛 3𝑥 2 𝑒 − 4 for each entry in x. The operations preceded by a ―dot‖ such as .* or
.^ are array operations. They allow entry-by entry multiplications or powers. Without the ―dot‖ these are
matrix operations. After creating the arrays x and y, an x-y plot is made. This method of doing calculations
is good for short, one-time-only calculations or for calculations where one does not wish to change any
parameters.
If we wish to execute repeatedly some set of commands, and possibly change input parameters as well,
then one should create a script M-file. Such a file always has a
".m" extension, and consists of the same commands one would use as input to a terminal.
To create a new script M-file, please follow the instructions on MATLAB interface. Please note that these
instructions are true for MATLAB R2011b. A new script file can also be created by Ctrl+N command
To create a new script file in previous versions of MATLAB, please follow the following instructions
6
[INTRODUCTION TO MATLAB] Signals and Systems
Now in order to execute the commands, write the following commands on command (terminal) window
>> myplot
Script M-files are ideal for repeating a calculation, but with some parameters changed. They are also useful
for doing demonstrations. As an exercise, create and execute the script file alteredplot.m:
Now, in order to execute the altered plot, write alteredplot on the command window. A menu bar will
appear and select the appropriate choice.
7
[INTRODUCTION TO MATLAB] Signals and Systems
Most of the M-files that one ultimately uses will be function M-files. These files again have the ―.m‖
extension, but they are used in a different way than scripts. Function files have input and output
arguments, and behave like FORTRAN subroutines or C-functions. In order to create a function M-file in
MATLAB R2011b follow the instructions
But in the previous versions of MATLAB, a function file is created as follows. The only difference is that
you have to write function initialization yourself.
function outputs=my_fun(inputs)
code
.
.
.
code
outputs=…..
Note that the word function appears at the start of the file, and in lower case letters. In addition, the
outputs and inputs and name of the function are listed. Let us return to the plot done in section 1.2.1.
Suppose that instead of giving the vector x, we want to make it a variable. At the same time, we want to
have available the data that we plotted. Here is a function file that would do this.
8
[INTRODUCTION TO MATLAB] Signals and Systems
Now, in order to execute the function M-file, there should be some input to the function on which the
function can execute. For example in the above case if we write my_fun on the command terminal an error
will occur that the input arguments are not available. So, in order to execute the function input arguments
must be given to the function, following command should be written on command terminal.
>> x=-pi:pi/40:pi;
>> my_fun(x)
Function files are normally used to combine functions in MATLAB to get new functions. For example,
suppose that we want to have at our disposal a function that computes the inverse of the square of a
matrix, and returns an error message if the matrix is close to singular or singular. Call this file inv_sq.m.
One more thing, in the code below, note that A^2 is used, not A.^2. This is because we are computing the
square of a matrix, not a matrix with the entries of A squared.
In general the most common form of the for loop (for use in a program, not on the command line) is
for index = j:k
statements
end
or
for index = j:m:k
statements
end
Note the following points carefully:
j:k is a vector with elements j, j + 1, j + 2, . . . , k.
j:m:k is a vector with elements j, j + m, j + 2m, . . . , such that the last element does not exceed k if m >
0 or is not less than k if m < 0.
9
[INTRODUCTION TO MATLAB] Signals and Systems
index must be a variable. Each time through the loop it will contain the next element of the vector j:k
or j:m:k, and statements (there may be one or more) are carried out for each of these values.
𝑛
𝑛 =1
(and can‘t remember the formula for the sum). Here‘s how to do it with a for loop (run the program, which
also times how long it takes):
t0 = clock;
s = 0;
for n = 1:100000
s = s + n;
end
etime(clock, t0)
The MATLAB function clock returns a six-element vector with the current date and time in the format year,
month, day, hour, minute, seconds. Thus, t0 records when the calculation starts. The function etime returns
the time in seconds elapsed between its two arguments, which must be vectors as returned by clock. On an
Intel Core 2 Duo processor with MATLAB 2011b, it returned about 0.2070 seconds, which is the total time
for this calculation. (If you have a faster PC, it should take less time.)
Now try to vectorize this calculation (before looking at the solution). Here it is:
t0 = clock;
n = 1:100000;
s = sum( n );
etime(clock, t0)
10
[INTRODUCTION TO MATLAB] Signals and Systems
This way takes only 0.04 seconds on the same PC—more than 50 times faster!
There is a neater way of monitoring the time taken to interpret MATLAB statements: the tic and toc
function. Suppose you want to evaluate:
𝑛=100000
1
𝑛2
𝑛=1
Here‘s the for loop version:
tic
s = 0;
for n = 1:100000
s = s + 1/nˆ2;
end
toc
which takes about 0.046065 seconds on the same PC. Once again, try to vectorize the sum:
tic
n = 1:100000;
s = sum( 1./n.ˆ2 );
toc
The same PC gives a time of about 0.05 seconds for the vectorized version—more than 100 times faster! (Of
course, the computation time in these examples is small regardless of the method applied. However,
learning how to improve the efficiency of computation to solve more complex scientific or engineering
problems will be helpful as you develop good programming skills.
q = pi;
while q > 0.01
q = q/2;
end
q =
0.0061
11
[INTRODUCTION TO MATLAB] Signals and Systems
2.4 Decisions
The MATLAB function rand generates a random number in the range 0–1. Enter the following two
statements at the command line:
r = rand
if r > 0.5 disp( ’greater indeed’ ), end
MATLAB should only display the message greater indeed if r is in fact greater than 0.5 (check by
displaying r). Repeat a few times—cut and paste from the Command History window (make sure that a
new r is generated each time).As a slightly different but related exercise, enter the following logical
expression on the command line: 2 > 0. Now enter the logical expression–1 > 0. MATLAB gives a value of 1
to a logical expression that is true and 0 to one that is false.
x = 2;
if x < 0 disp( ’neg’ ), else disp( ’non-neg’), end
12
[INTRODUCTION TO MATLAB] Signals and Systems
do you get the message non-neg? If you change the value of x to−1 and execute the if again, do you get the
message neg this time?
Most banks offer differential interest rates. Suppose the rate is 9% if the amount in your savings account is
less than $5000, but 12% otherwise. The Random Bank goes one step further and gives you a random
amount in your account to start with! Run the following program a few times:
1.4.4 elseif
Suppose the Random Bank now offers 9% interest on balances of less than $5000, 12% for balances of $5000
or more but less than $10,000, and 15% for balances of $10,000 or more. The following program calculates a
customer‘s new balance after one year according to this scheme:
13
[INTRODUCTION TO MATLAB] Signals and Systems
Graphs (in 2D) are drawn with the plot statement. In its simplest form, plot takes a single vector
argument, as in plot(y). In this case, the elements of y are plotted against their indexes. For example,
14
[INTRODUCTION TO MATLAB] Signals and Systems
plot(rand(1, 20)) plots 20 random numbers against the integers 1–20, joining successive points with straight
lines, as in Figure 2.1. Axes are automatically scaled and drawn to include the minimum and maximum
data points. For example,
>> plot(rand(1,20))
Probably the most common form of plot is plot(x, y), where x and y are vectors of the same length:
>> x=0:pi/40:4*pi;
>> plot(x, sin(x))
Straight-line graphs are drawn by giving the x and y coordinates of the end points in two vectors. For
example, to draw a line between the points with Cartesian coordinates (0, 1) and (4, 3), use the statement
15
[INTRODUCTION TO MATLAB] Signals and Systems
That is, [0 4] contains the x coordinates of the two points, and [1 3] contains the y coordinates.
MATLAB has a set of easy-to-use plotting commands, all starting with the string ez. The easy-to-use form
of plot is ezplot. It is important to note that there is no requirement of a vector x in order to execute
the ezplot command. This command is mostly used in order to plot the build in trigonometric function of
MATLAB such as acos(x), cosh(x) etc.
>> ezplot(’tan(x)’)
2.5.1.1 Labels
gtext(’text’) writes a string (text) in the graph window. It puts a crosshair in the graph window
and waits for a mouse button or keyboard key to be pressed. The crosshair can be positioned with the
mouse or the arrow keys. For example, gtext( ’X marks the spot’ )
16
[INTRODUCTION TO MATLAB] Signals and Systems
Text may also be placed on a graph interactively with Tools→Edit Plot from the figure window. grid
adds/removes grid lines to/from the current graph. The grid state may be toggled.
text(x, y, ’text’) writes text in the graphics window at the point specified by x and y. If x
and y are vectors, the text is written at each point. If the text is an indexed list, successive points are labeled
with its corresponding rows.
There are at least two ways of drawing multiple plots on the same set of axes (which may however be
rescaled if the current data falls outside the range of the previous data).
Simply to use hold to keep the current plot on the axes. All subsequent plots are added to the axes until
hold is released, with either hold off or just hold, which toggles the hold state.
Use plot with multiple arguments. For example,
plot(x1, y1, x2, y2, x3, y3, ... )
plots the (vector) pairs (x1, y1), (x2, y2), and so on. The advantage of this method is that the vector pairs
may have different lengths. MATLAB automatically selects a different color for each pair. If you are
plotting two graphs on the same axes, you may find plotyy useful—it allows you to have
17
[INTRODUCTION TO MATLAB] Signals and Systems
Line styles, markers, and color for a graph may be selected with a string argument to plot. For example,
plot(x, y, ‘--‘) joins the plotted points with dashed lines, whereas plot(x, y, ‘o‘) draws circles at the data
points with no lines joining them. You can specify all three properties: plot(x,sin(x), x, cos(x), ‘om--‘) which
plots sin(x) in the default style and color and cos(x) with circles joined by dashes in magenta. The available
colors are denoted by the symbols c, m, y, k, r, g, b, w.
which sets the scaling on the current plot. In other words, draw the graph first, then reset the axis limits.
If you want to specify the minimum or maximum of a set of axis limits and have MATLAB autoscale the
other, use Inf or -Inf for the autoscaled limit.
You can show a number of plots in the same figure window with the subplot function. It looks a little
curious at first, but getting the hang of it is quite easy. The statement
subplot(m,n,p)
divides the figure window into m × n small sets of axes and selects the pth set for the current plot
(numbered by row from the left of the top row). For example,
18
[INTRODUCTION TO MATLAB] Signals and Systems
semilogy(x, y)
plots y with a log10 scale and x with a linear scale. For example,
x = 0:0.01:4;
semilogy(x, exp(x)), grid
produce the graph in figure below. Equal increments along the y-axis represent multiples of powers of 10,
so, starting from the bottom, the grid lines are drawn at 1, 2, 3, . . . , 10, 20, 30. . . , 100, . . . . Incidentally, the
graph of ex on these axes is a straight line because the equation y = ex transforms into a linear equation when
you take logs of both sides.
19
[ Fall 2012] [INTRODUCTION TO MATLAB] Signals and Systems
2.5.1.7 Hold:
A call to plot clears the graphics window before plotting the current graph. This is not convenient if we
wish to add further graphics to the figure at some later stage. To stop the window being cleared hold
command is used. Let us see the following example:
clear all
close all
t=0:0.001:1;
x=sin(2*pi*t);
y=cos(2*pi*t);
plot(t,x,'r--'), grid on, hold on
plot(t,y,'b-')
2.5.1.8 3D plots:
MATLAB also helps in 3D plotting of functions. 3D plotting is in fact beyond the scope of this lab but some
command for 3D plotting that you should be familiar with are given below: Consider the following
commands for 3D plotting
t = -4*pi:pi/16:4*pi;
x = cos(t);
y = sin(t);
z = t;
figure(1), plot3(x,y,z),grid on
[x, y] = meshgrid(-3:0.1:3,-3:0.1:3);
z = x.^2 - y.^2;
figure(2),mesh(x,y,z),grid on
figure(3),surf(x,y,z), grid on
figure(4),plot3(x,y,z),grid on
20
[INTRODUCTION TO MATLAB] Signals and Systems
21
[INTRODUCTION TO MATLAB] Signals and Systems
clear all;
close all;
n=-10:10;
y=sin(2*pi/10*n);
stem(n,y,'fill','Linewidth',2), grid on
xlabel('Sequences'); ylabel('Magnitude');
title('Discrete Time Sine Function');
22
[INTRODUCTION TO MATLAB] Signals and Systems
Tasks
In-Lab Task 01: Make a function ‗my_sum‘ which takes two vectors x and y as input. The vectors
should have different sizes. Firstly, make size of both the input vectors same by padding
(concatenating) zeros. Now add both the vectors element wise. The function should return a
variable z which should contain the sum of all the elements of the vectors formed as a result of
summation of input vectors x and y.
In-Lab Task 02: Plot a function 𝑒 −0.2𝑥 𝑠𝑖𝑛 𝑥 between the interval 0 𝑡𝑜 6𝜋 .
In-Lab Task 03: Write MATLAB programs to find the following with for loops and
vectorization. Time both versions in each case.
a) 12 + 22 + 32 + 42 + ⋯ + 10002
1 1 1 1 1
b) 1 − + − + − ⋯ ⋯ −
3 5 7 9 1003
In-Lab Task 04: Graph the following function in MATLAB over the range
of 0 to 10. sin 𝑥 , sin 𝑥 > 0
𝑦 𝑥 =
0, (sin 𝑥 ≤ 0)
2
In-Lab Task 05: Use the semi log graph to graph, 𝑥 4 𝑎𝑛𝑑 𝑒 𝑥 over the interval of 0 ≤ 𝑥 ≤ 2𝜋.
Post-Lab Task 01: Plot the first ten cycles of sinusoid (sin) with time period of 2 seconds. The
horizontal axis corresponds to time period while vertical axis depicts the values of sinusoid.
23
[INTRODUCTION TO MATLAB] Signals and Systems
The profile of the sinusoids with dotted lines and solid line should show the sinusoid.
24