You are on page 1of 15

Daffodil International University

Department of Electrical and Electronic Engineering


EEE 322: Digital Signal Processing Laboratory

EXPERIMENT NO: 02

NAME OF THE EXPERIMENT: SCRIPT FILES IN MATLAB

Why Script Files


In the previous experiment, the commands were executed in the command window. Although every MATLAB
command can be executed in this way, there are some drawbacks of using command window:
(i) Using the command window to execute a series of commands (especially if they are related to each other) is not
convenient and may be difficult or even impossible.
(ii) The commands in the command window cannot be saved and executed again.
(iii) The command window is not interactive. This means that, every time the ENTER key is pressed, only the last
command is executed and everything executed before is unchanged. If a change or correction is needed in a
previous command,the commands have to be entered again.
A different way of executing commands with MATLAB is first to create a file with a list of commands, save it and
then run the file. The files that are used for this purpose is called ​script​ files.

Creating and Saving a script file


In MATLAB, script files are created and edited in the ​Editor/Debugger window. To do so, follow: ​File→ New→
M-File​.You will see the following window:
Before a script file can be executed it has to be saved. This is done by choosing save as from the file menu, selecting
a location and entering a name for the file.

Running a script file


A script file can be executed in several ways:
Directly from the editor window –
(i) Click the ​Run​ icon (see Fig. 2.1)
(ii) Follow: ​debug → ​ ​ run <file_name.m>
​ 5​ button in keyboard
(iii) Press F
Or, indirectly from the command window –
Type ​filename​ in the command window and press ​Enter

Example 1
Voltage Divider: ​In an electrical circuit if several resistors are connected in series, the voltage across each of them
is given by the voltage divider rule:
Rn
Vn = V
Req s
Where, V n and Rn are the voltage across n​th​ resistor, Rn .

Req is the equivalent resistance of the connection ( Req = ∑ Rn


n
) .

The power dissipated in the n​th ​resistor is given by:


2
Pn =
V n2
Rn
= 1
Rn ( Rn
V
Req s ) =
Rn
2
Req
V s2
Write a program in script file, which calculates the voltage across each resistor and power dissipated in each resistor,
in a series circuit in Fig. 2.2. When the script file is executed, it prompts the user to first enter the source voltage and
then to enter the resistance of the resistors in a vector. The program displays the result in a table. Following the
table, the program displays the current in the circuit, and the total power. Run the program and enter the following
data for V s and the R ’s.
V s = 24 V , R1 = 20 Ω, R2 = 14 Ω, R3 = 12 Ω, R4 = 18 Ω, R5 = 8 Ω, R6 = 15 Ω, R7 = 10 Ω

​ reate the m-file as in the editor window given below:


Solution: C

1
 After executing the script file in the command window ,the output is as follows:

Controlling Execution Flow


It is possible to do a great deal in MATLAB by simply executing statements involving matrix expressions, one after
the other. However, there are cases in which one simply must substitute some non-sequential order. To facilitate
this, MATLAB provides three relatively standard methods for controlling program flow: the ​if-else ​statement,
the ​for ​loop and the ​while ​loop.

Examples of control flow statements


if-else
num = -3;
if num > 0
x = ’positive’;
elseif num < 0
x = ’negative’;
elseif num == 0
x = ’zero’;
else
x = ’error’;
end
Question: ​What is the value of ’​x​’ after execution of the above code?

while
x = -10;
while x < 0
x = x + 1;
end
Question: ​What is the value of ​x​ after execution of the above code?

for
x = 0;
for i = 1:10
x = x + 1;

2
end
Question:​ What is the value of ​x​ after executing the above code?

switch
x = 10;
switch x
case 5
disp(‘x is 5’)
case 6
disp(‘x is 6’)
case 8
disp(‘x is 8’)
case 10
disp(‘x is 10’)
otherwise
disp(‘invalid choice’)
end
Question:​ What is the output shown after executing the above code?

break
The ​break​ statement lets you exit early from a ​for​ or ​while​ loop:
x = -10;
while x < 0
x = x + 2;
if x == -2
break;
end
end
Question:​ What is the value of ​x​ after executing the above code?

Relational and Logical Operators


MATLAB supports the following relational and logical operators:
Relational Operators Logical Operators
Symbol Meaning Symbol Meaning
<= Less than or equal to & AND
< Less than | OR
>= Greater than or equal to ~ NOT (unlike ​C.​ In ​C,​ it was​!​’)
> Greater than
== Equal to
Not equal to
~=
(unlike ​C​. In ​C​, it was ‘​!=​’)

3
Example 2
Write a script file to sum the series 1 + 2 + 3 + ⋯⋯⋯ + n , n taken from user.

Solution:

Executing from command window

4
Writing User-defined Functions
A function file starts with a line declaring the function with its name, input arguments and outputs. Then, follows the
statements required to produce the outputs from the inputs.
Example: Suppose, we want to calculate average of some numbers. For this purpose, let us create a function named
average.m​. The steps are:
(i) Open a new m-file from editor.
(ii) Write the following code as shown in the figure:

Structure of a function definition line


function [output_arguments] = ​function_name(​ input_arguments)

Body of a function
The function body contains the computer program (code) that actually performs the computation. The code can use
all MATLAB programming features. This includes calculations, assignments, any built-in or another user-defined
functions, flow control etc. You can now understand the function as shown in Fig. 2.6.

5
How to use a user-defined function
We can call a function from the command window as show in the following Fig. 2.7.

Figure 2.7: Calling our function ​average.m​ from command window

Example 3
Write a function that takes radius as input and find the area and perimeter of a circle.
​ he function is defined as follows:
Solution: T

Create it in m-file script and save as ​circle.m

Calling ​circle.m​ function from command window:

2-D Plotting in MATLAB


Plots are very useful tools for presenting information. MATLAB has many commands that can be used for creating
different types of plots. We will discuss some of them now.

6
plot​ command
The ​plot​ command is used to create two-dimensional plots. The simplest form of the command is:
plot(x,y)
​ lot​ command to draw simple curve.
Example: p

The commands on the command window give the


following figure:

The ​plot​ command has additional optional arguments that


can be used to specify the color and style of the line and the
color and type of markers,if any are desired.With these
options the command has the form:

Line Specifiers
Line specifiers are optional and can be used to define the style and color of the line and type of the markers (if the
markers are used).

Line-style Specifiers Used to specify the color of the line:


Used to define the style of the line i.e. – solid line, Line-color Specifier
dashed line and so on.
Red r
Line-style Specifier Green g
Solid (default) - Blue b
Dashed -- Cyan c
Dotted . Magenta m
Dash-dot -. Yellow y
Pointed o Black k
White W

Line​-​color Specifiers
Marker-type Specifiers
Marker type specifiers are used to define the type of the markers (when markers are used).
Marker-type Specifier
Plus Sign +
Circle o
Asterisk *
Point .
Square s

7
Diamond d
Five-point Star p
Six-point Star H

Some Examples

Command Meaning
plot(x, y) A blue solid line connecting the points with no markers (default)
plot(x, y, ’r’) A red solid line connecting the points.
plot(x, y, ’--y’) A yellow dashed line connecting the lines
plot(x, y, ’*’) The points are marked with * (no line between points)
A green dotted line connecting the points that are marked with
plot(x, y, ’g:d’)
diamond markers.

Example 4
Suppose the following given data is used to create vectors
that are then used in the ​plot​ command.
Year 2002 2003 2004 2005 2006 2007 2008
Sales(millions) 8 12 20 22 18 24 27
To plot this data, the following codes are written in the
command window:

And the output figure will be as the following:

Plot of Given Functions


In many situations, there is a need to plot a given function.
This can be done in MATLAB by using ​plot​ or ​fplot​ function.
(i) Using ​plot​ function
Suppose we want to plot the function –
−x
y = (3.5) 2 cos cos (6x) , − 2≤x≤4
The program that plots this function is shown in the
following commands:

And the output figure will be as the following:

(ii) Using ​fplot​ function


The commands will be:

8
The output figure is the same as above.

Plotting Multiple Graphs in the same plot


There are three ways to do so:
(i) Using ​plot​ command with pair of vectors inside it
(ii) Using ​hold on​ and ​hold off​ command
(iii) Using ​line​ command

Example 5
Plot the function y = 3x3 − 26x + 6 and its first and second derivatives for − 2≤x≤4 , all in the same plot.

Solution:
x = -2:0.01:4;
y = 3*x.^3-26*x+6;
yd = 9*x.^2-26;
ydd = 18*x;

% using ‘plot’ command


plot(x, y, '-b',...
x, yd, '--r',...
x, ydd, ':k')

% using ‘hold’ command


figure(2)
plot(x, y, '-b')
hold on
plot(x, yd, '--r')
plot(x, ydd, ':k')
hold off

% using ‘line’ command


figure(3)
plot(x, y, 'linestyle', '-', 'color', 'b')
line(x, yd, 'linestyle', '--', 'color', 'r')
Any one of the three commands will give the desiredplot in a single figure as shown in Fig. 2.8.

Formatting a plot using commands


The formatting commands are placed after the ​plot or ​fplot commands .The various formatting commands are
shown in the following table:
Labeling the Axes
Command Purpose
xlabel(‘string’)
To label the x-axis and y-axis by text.
ylabel(‘string’)

9
title(‘string’) To give a title to your figure
text(x, y, ’string’)
To place a text anywhere on the figure.
gtext(‘string’)
legend(‘string1’, ’string2’) To place a legend on the plot

Setting Limits on Axes


Command Purpose
Sets the limits of the x-axis
axis([xmin, xmax])
(​xmin​ and ​xmax​ are numbers)
axis([xmin, xmax, ymin, ymax]) Sets the limits of both the axis
axis equal Sets the same scale for both the axis
axis square Sets the axis region to be square

Setting Gridline ON/OFF


Command Purpose
grid on Adds grid line to the plot
grid off Removes grid line from the plot

Making plot of discrete-time plots

Use of ​stem
The function ​stem is used to plot discrete-time
functions (in contrast to the ​plot function, which is
used to plot continuous-time functions).
Example 6
Observe the following code:
>> x = 0:1:10;
>> y = sin(x);
>> stem(x, y)

This will give the plot in Fig. 2.9.

Figure 2.9: Plotting discrete-time functions


The command divides the figure window (page when
Plotting Multiple Plots on the Same Figure printed) into ​m × n rectangular subplots where plots
Use of ​subplot will be created. ​k​ varies from ​1​ to ​mn​ row-wise.
Multiple plots on the same page can be created with
the ​subplot​ command which has the form: For example, the commands ​subplot(3,2,1) …
subplot(m, n, k) subplot(3,2,6)​will create the arrangement as
shown in Fig. 2.10.

10
11
Example 7
The figure shows a simple high-pass filter consisting of a resistor and a capacitor. The ratio of the output voltage
V o to the input V i is given by:
Vo j2πf RC
Vi
= 1+j2πf RC

Assume R = 16 kΩ and C = 1 μF . Calculate and plot the amplitude and


phase response of this filter as a function of frequency.

​ he script file is as follows:


Solution:T

The output figure is as follows:

12
REPORT
[Submit in the next session]
Q1. Write MATLAB script to plot sin sin 2x and its derivative on the same plot in two different colors and in three
different ways.

Q2. A resistor of value R = 4 Ω and an inductor of value L = 1.3 H are connected in series to a voltage source, as
shown in the figure (a).

When the voltage source applies a rectangular voltage pulse with an amplitude of V = 12 V and a duration of
0.5 s , as shown in figure (b). The current i (t) is given by:

Make a plot of the current as a function of time for 0≤t≤2 sec .

Q3. The figure shows a simple low-pass filter consisting of a resistor and a capacitor.

n
Assume R = n kΩ and C = 20 μF , where n is the ​last two digits of your student ID​. Calculate the amplitude
and phase response of this filter as a function of frequency and plot them in a single figure using ​subplot​.
V 1
[​Hint:​Gain of a low-pass filter is given by: V o = 1+jωRC ].
i

Reference Books:
(1) “Duane Hanselman, Bruce Littlefield “, Mastering MATLAB 7
(2) “Amos Gilat”, MATLAB An introduction with Applications
Web resource​: ​www.mathworks.com

13
14

You might also like