0% found this document useful (0 votes)
10 views

Lab 2 SP18

This document introduces basic MATLAB commands including logical and relational operators, loops, decision statements, and plotting. It provides tables of the various operators and functions in MATLAB and describes their usage and precedence. Examples are given to demonstrate relational, logical, and conditional expressions.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

Lab 2 SP18

This document introduces basic MATLAB commands including logical and relational operators, loops, decision statements, and plotting. It provides tables of the various operators and functions in MATLAB and describes their usage and precedence. Examples are given to demonstrate relational, logical, and conditional expressions.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 24

[INTRODUCTION TO MATLAB] Signals and Systems

LAB # 02

Introduction to MATLAB

1
[INTRODUCTION TO MATLAB] Signals and Systems

Lab 02-Introduction to MATLAB


Lab Objective
The objective of this lab is to get familiar with MATLAB environment and implement some basic
commands for logical and relational operators. This lab also includes loops and decison statements
understanding. At the end plotting in MATLAb is discussed.

Table 2.1: Relational Operators in MATLAB


Operator Description
< Greater than
<= Greater than or equal to
> Less than
>= Less than or equal to
== Equal to
~= Not equal to

2.1 Logical and Relational Operators in MATLAB


2.1.1 Relational Operators:

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.

>> A = [1 2; 3 4]; B = 2*ones(2);


>> A == B
ans =
0 1
0 0
» A > 2
ans =
0 0
1 1
>> A > B
ans =
0 0
1 1
>> A < B
ans =
1 0
0 0
>> A >= B
ans =
0 1
1 1

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:

>> A = [1 inf; -inf NaN]


A =
1 Inf
-Inf NaN
>> isinf(A)
ans =
0 1
1 0

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

>> [isreal(a) isreal(b) isreal(c)]


ans =
1 0 1

3
[INTRODUCTION TO MATLAB] Signals and Systems

Table 2.2: is functions


Command Description
ischar Test for char array (string)
isempty Test for empty array
isequal Test if arrays are equal
isequalwithequalnans Test if arrays are equal, treating NaNs as equal
isfinite Detect finite array elements
isfloat Test for floating point array (single or double)
isinf Detect infinite array elements
isinteger Test for integer array
islogical Test for logical array
isnan Detect NaN array elements
isnumeric Test for numeric array (integer or floating point)
isreal Test for real array
isscalar Test for scalar array
issorted Test for sorted vector
isvector Test for vector array

2.1.2 Logical Operators:


There are certain logical operators in MATLAB as well. A list of these logical operators is given in Table 2.3

Table 2.3: Logical Operators in MATLAB


Operator Description
& Logical AND
&& Logical AND for scalars
| Logical OR
|| Logical OR for scalars
~ Logical NOT
xor Exclusive OR
all True if all elements of a vector are non zero
any True if any element of the vector is non zero

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

>> all(x > 0)


ans =
0
Note that xor must be called as a function: xor (a,b). The and, or, and not operators and the relational
operators can also be called in functional form as and(a,b) etc. The operators && and || are special in two
ways. First, they work with scalar expressions only, and should be used in preference to & and | for scalar
expressions.

>> any(x>0) && any(y>0)


ans =
1
>> x>0 && y>0
??? Operands to the 11 and && operators must be convertible to
logical scalar values.

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.

2.1.3 Precedence of Operators:


The precedence of arithmetic, relational, and logical operators is summarized in Table 2.4 (which is based
on the information provided by help precedence). For operators of equal precedence MATLAB evaluates
from left to right. Precedence can be overridden by using parentheses. Note, in particular, that and has
higher precedence than or, so a logical expression of the form

Table 2.4: Precedence of Operators


Precedence Level Operator
1 (highest) Parentheses ()
2 Transpose (. ' ) > power (.^), complex conjugate,
3 Unary plus (+), unary minus (-), logical negation (~)
4 Multiplication (.*), right division (./), left division
5 Addition(+), Subtraction(-)
6 Colon operator (:)
7 Less than (<), less than or equal to (<=), greater
than (>), greater than or equal to (>=), equal to (==),
not equal to (~=)
8 Logical AND (&)
9 Logical OR (|)
10 Logical short circuit AND (&)
11(lowest) Logical short circuit OR (|)

2.2 MATLAB M files


There are four ways of doing code in MATLAB. One can directly enter code in a terminal window. This
amounts to using MATLAB as a kind of calculator, and it is good for simple, low-level work. The second

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.

2.2.1 Terminal Input


𝑥2
One can type the code in the MATLAB terminal window. For example, if we wish to plot 𝑥𝑠𝑖𝑛 3𝑥 2 𝑒 − 4
between the interval [−𝜋, 𝜋], we could type the following in the terminal window.

>> 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.

2.2.2 Script M files:

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.

2.2.2.1 Create a Script M-file:

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

File New Script

To create a new script file in previous versions of MATLAB, please follow the following instructions

File New M-file


For example, to do the plot in section 1.2.1, one would create the file myplot.m:

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

2.2.3 Function M-files:

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

File New Function

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.

File New M-file

The structure of a typical function file, say my_fun.m, is as follows:

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.

function B=inv sq(A)


if abs(det(A))< 0.0001,
error('The matrix is singular')
else
B=inv(A^2);
end

2.3 Loops in MATLAB


Loops are MATLAB constructs that permit us to execute a sequence of statements more than once. There
are two basic forms of loop constructs while loops and for loops. The major difference in these two types of
loops is in how the repetition is controlled. The code in a while loop is repeated an indefinite number of
times until some user specified condition is satisfied. By contrast, the code in a for loop is repeated for a
specified number of times, and the number of repetitions is known before the loops start.

2.3.1 The basic for construct

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.

2.3.2 for in a single line


If you insist on using for in a single line, here is the general form:
for index = j:k, statements, end
or
for index = j:m:k, statements, end
Note the following:
 Don‘t forget the commas (semicolons will also do if appropriate). If you leave them out you will get
an error message.
 Again, statements can be one or more statements separated by commas or semicolons.
 If you leave out end, MATLAB will wait for you to enter it. Nothing will happen until you do so.

2.3.3 Avoid for loops by vectorizing!


There are situations where a for loop is essential, as in many of the examples in this section so far.
However, given the way MATLAB has been designed, for loops tend to be inefficient in terms of
computing time. If you have written a for loop that involves the index of the loop in an expression, it may
be possible to vectorize the expression, making use of array operations where necessary, as the following
examples show. Suppose you want to evaluate:
100000

𝑛
𝑛 =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.

2.3.4 While Loop

Syntax for while loop is


while expression
statements
end
This loop is used when the programmer does not know the number of repetitions a priori. Here is an
almost trivial problem that requires a use of this loop. Suppose that the number is divided by 2. The
resulting quotient is divided by 2 again. This process is continued till the current quotient is less than or
equal to 0.01. What is the largest quotient that is greater than 0.01?
To answer this question we write a few lines of code

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.

2.4.1 The one-line if statement


In the last example MATLAB has to make a decision; it must decide whether or not r is greater than 0.5.
The if construct, which is fundamental to all computing languages, is the basis of such decision making.
The simplest form of if in a single line is
if condition statement, end
Note the following points:
 condition is usually a logical expression (i.e., it contains a relational operator), which is either true or
false. MATLAB allows you to use an arithmetic expression for condition. If the expression evaluates
to 0, it is regarded as false; any other value is true. This is not generally recommended; the if
statement is easier to understand (for you or a reader of your code) if condition is a logical
expression.
 If condition is true, statement is executed, but if condition is false, nothing happens.
 condition may be a vector or a matrix, in which case it is true only if all of its elements are nonzero. A
single zero element in a vector or matrix renders it false.
Here are more examples of logical expressions involving relational operators, with their meanings in
parentheses:

b^2 < 4*a*c (b2 < 4ac)


x >= 0 (x ≥ 0)
a ~= 0 (a ≠ 0)
b^2 == 4*a*c (b2= 4ac)
Remember to use the double equal sign (==) when testing for equality:
if x == 0 disp( ’x equals zero’), end
1.4.2 The if-else construct
If you enter the two lines

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:

bal = 10000 * rand;


if bal < 5000
rate = 0.09;
else
rate = 0.12;
end
newbal = bal + rate * bal;
disp( ’New balance after interest compounded is:’ )
format bank
disp( newbal )
Display the values of bal and rate each time from the command line to check that MATLAB has chosen the
correct interest rate.
The basic form of if-else for use in a program file is
if condition
statementsA
else
statementsB
end
Note that
 statementsA and statementsB represent one or more statements.
 If condition is true, statementsA are executed, but if condition is false, statementsB are executed. This is
essentially how you force MATLAB to choose between two alternatives.
 else is optional.

1.4.3 The one-line if-else statement


The simplest general form of if-else for use on one line is
if condition statementA, else statementB, end
Note the following:
 Commas (or semicolons) are essential between the various clauses.
 else is optional.
 end is mandatory; without it, MATLAB will wait forever.

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

bal = 15000 * rand;


if bal < 5000
rate = 0.09;
elseif bal < 10000
rate = 0.12;
else
rate = 0.15;
end
newbal = bal + rate * bal;
format bank
disp( ’New balance is:’ )
disp( newbal )
Run the program a few times, and once again display the values of bal and rate each time to convince
yourself that MATLAB has chosen the correct interest rate. In general, the elseif clause is used:
if condition1
statementsA
elseif condition2
statementsB
elseif condition3
statementsC
...
else
statementsE
end
This is sometimes called an elseif ladder. It works as follows:
1. condition1 is tested. If it is true, statementsA are executed; MATLAB then moves to the next statement
after end.
2. If condition1 is false, MATLAB checks condition2. If it is true, statementsB are executed, followed by
the statement after end.
3. In this way, all conditions are tested until a true one is found. As soon as a true condition is found,
no further elseifs are examined and MATLAB jumps off the ladder.
4. If none of the conditions is true, statementsE after else are executed.
5. Arrange the logic so that not more than one of the conditions is true.
6. There can be any number of elseifs, but at most one else.
7. elseif must be written as one word.
8. It is good programming style to indent each group of statements as shown.

2.5 Plotting in MATLAB:


2.5.1 Basic Two Dimensional Graphs:

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))

Figure 2.1 Plot of 20 random numbers

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))

Figure 2.2 Plot of sine function

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

plot([0 4], [1 3])

15
[INTRODUCTION TO MATLAB] Signals and Systems

Figure 2.3 Plot of numbers

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)’)

Figure 2.4 Plot of tangent function using ezplot

2.5.1.1 Labels

Graphs may be labeled with the following statements:

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.

title(’text’) writes the text as a title at the top of the graph.

xlabel(’horizontal’) labels the x-axis.

ylabel(’vertical’) labels the y-axis.

2.5.1.2 Multiple plots on the same axes:

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

independent y-axis labels on the left and the right:


plotyy(x,sin(x), x, 10*cos(x))

Figure 2.5 plotyy command

17
[INTRODUCTION TO MATLAB] Signals and Systems

2.5.1.3 Line styles, markers, and color:

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.

Table 2.4: Line Styles and Colours in MATLAB


Colours Line Styles
Yellow Y Point .
Magenta M Circle o
Cyan C X-mark x
Red R Plus +
Green G Solid -
Blue B Star *
While W Dotted :
Black K Dashed dot -.
Dashed --

2.5.1.4 Axis limits:


Whenever you draw a graph, MATLAB automatically scales the axis limits to fit the data. You can override
this with
axis( [xmin, xmax, ymin, ymax] )

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.

2.5.1.5 Multiple plots in a figure: subplot:

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

Figure 2.6 Plot using subplot command

2.5.1.6 Logarithmic Plots:


The command

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.

Figure 2.7 logarithmic Plot

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-')

Figure 2.8 Hold on command

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

Figure 2.9 3D Plots

2.5.1.8 Various plotting functions:

MATLAB supports various types of graph and surface plots such as

 dimensions line plots (x vs. y),


 filled plots,
 bar charts,
 pie charts,
 parametric plots,
 polar plots,
 contour plots,
 density plots,
 log axis plots,
 surface plots,
 parametric plots in 3 dimensions
 and spherical plots.

21
[INTRODUCTION TO MATLAB] Signals and Systems

2.6 Plotting Discrete Time Sequences in MATLAB


The plot of continuous time signals in MATLAB is an artificial concept because MATLAB only deals with
discrete data noting is continuous in MATLAB. In order to generate a continuous time signal the increment
is so small that MATLAB artificially plots a continuous time signal. In order to draw a discrete time signal
stem command is used and an example is given below.

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.

Post-Lab Task 02: Plot the following discrete sequences


a. 𝑥 𝑛 = 𝛼 𝑛 0 ≤ 𝑛 ≤ 10, 𝛼 = 1.5
b. 𝑥 𝑛 = 𝛽 𝑛
− 10 ≤ 𝑛 ≤ −1, 𝛽 = 1.5
c. 𝑥 𝑛 = 𝛾 𝑛
0 ≤ 𝑛 ≤ 10, 𝛾 = 0.5
𝑛
d. 𝑥 𝑛 = 𝜑 − 10 ≤ 𝑛 ≤ −1, 𝜑 = 0.5
Horizontal axis corresponds to instances n and vertical axis depicts 𝑥[𝑛] values.

Post-Lab Task 03: 𝑥 𝑡 = 𝐴 ℝ 𝑒 𝑗 (𝜔 0 𝑡+𝜑)


Where A = 1, f0 = 10 Hz, 𝜑 = 0
Plot the second and third harmonics of the above sinusoid. Use SUBPLOT command for drawing
in the same manner as in previous question. After plotting explain the relation of fundamental
Time period and harmonics Time period clearly. Your answer should corroborate the graphs
drawn.

23
[INTRODUCTION TO MATLAB] Signals and Systems

Post-Lab Task 04: Plot


𝑟𝑡
𝑥 𝑡 = 𝐶𝑒 cos(𝜔𝑡 + 𝜑)

1. C = 2, f = 100 Hz, and 𝜑 = 0, r = 0.01


2. C = 2, f = 100 Hz, and 𝜑 = 0, r = -0.01

The profile of the sinusoids with dotted lines and solid line should show the sinusoid.

24

You might also like