You are on page 1of 19

Signals and Systems

(EL-223)

LABORATORY MANUAL
Spring 2020

Dr. Shahzad Saleem


Engr. Fakhar Abbas
Functions, Control Flow and Plotting in Matlab
(LAB # 03)
Student Name: ______________________________________________
Roll No: ________________ Section: ____
Date performed: _____________, 2020

MARKS AWARDED: ________ / 20

________________________________________________________________________________________________________________________________________________________
NATIONAL UNIVERSITY OF COMPUTER AND EMERGING SCIENCES, ISLAMABAD

Prepared by: Engr. Fakhar Abbas Version: 2.01


Verified by: Dr. Waqas bin Abbas, Ms. Shahzad Saleem

SIGNALS AND SYSTEMS LAB NUCES FAST, ISLAMABAD Page 1 of 19


Functions, Control Flow and Plotting in MATLAB LAB 3
Lab # 03: Functions, Flow Control and Plotting in MATLAB
Objective:
In this lab, you will learn:
How to create functions and script files?
Input and output function
Nested Functions
Control flow statements
Two dimensional plot
Plot formatting
Displaying multiple plots
Debugging a code in MATLAB environment.

Tools Used: MATLAB

Description:
M-file:

• MATLAB can execute a sequence of MATLAB


statements stored on disk. Such files are called
"M-files"
• They must have the file type of ".m"
• To make the m-file click on New and then click
on Script from the pull-down menu as shown in
“Fig 2.1”. “Ctrl+N” can also be used for this
purpose.

Figure 2.1

You will be presented with the MATLAB Editor/Debugger screen as shown in “Fig 2.2”

“Fig 2.2”

• Here you will type your code, can make changes, etc.
• Once you are done with typing, click on File, in the MATLAB Editor/Debugger screen and
select Save As…

SIGNALS AND SYSTEMS LAB NUCES FAST, ISLAMABAD Page 2 of 19


Functions, Control Flow and Plotting in MATLAB LAB 3
• Choose a name for your file, e.g., firstgraph.m. Click on Save.
• Make sure that your file is saved in the directory that is in MATLAB's search path.
• There are two types of M-files:
1- Script files
2- Function files.

Script Files:
• Script files do not take the input arguments or return the output arguments
• Example (plotxy.m)
x = [1 2 3; 4 5 6]
y = [2 3 4; 6 7 8]
plot(x,y)

Function Files:
• The function files may take input arguments or return output arguments.
• Function Definition
• The first line of a function m-file must be of the following form

function [out_param_list] = funct_name (in_param_list)

• Following the ‘function’ keyword , the (optional) output parameters are enclosed in square
brackets [ ]
• If the function has no output_parameter_list the square brackets are omitted and a single
keyword is used. In that case the first line of a function m-file must be of the following form

function funct_name (in_param_list)

• The function_name is a character string that will be used to call the function
• The function_name must also be the same as the file name (without the ``.m'') in which the
function is stored Example:

SIGNALS AND SYSTEMS LAB NUCES FAST, ISLAMABAD Page 3 of 19


Functions, Control Flow and Plotting in MATLAB LAB 3

• Function Calling: Function can either be called from “ M- File” or a “Command window”.
For above example function will be called in a following way:

function y =mean(x)

• The input_parameter_list and output_parameter_list are comma-separated lists of MATLAB


variables in the case of multiple input and output parameters.
• The input and output variables can be scalars, vectors, matrices, and strings

Example:

Function to compute the length of the hypotenuse of right triangle given the lengths of the
other two sides
a - The length of one side
b - The length of the other side
c - The length of the hypotenuse

function c =
hyp(a,b) c =
sqrt(a^2 + b^2) ;
end

• Function calling
C = hyp(1,2)

SIGNALS AND SYSTEMS LAB NUCES FAST, ISLAMABAD Page 4 of 19


Functions, Control Flow and Plotting in MATLAB LAB 3

Input/Output Functions:

Input Function:
• Syntax : Prompt for user input
• Format : input(‘String to display’) Description:
Input function is used to get data from user and prompts until data has been entered.
• Example;
>> marks = input (‘Enter total marks = ’)
Enter total marks = 5
marks =
5

Disp Function:
• Syntax : Display array
• Format : disp(variable_name), disp(‘String to display’) Description:
Displays the array, without printing the array name. In all other ways it's the same as
leaving the semicolon off an expression except that empty arrays don't display.
Example;
>> disp(‘ hello ’)
>> a=[1 3 5];
>> disp(a)

Control Flow Statements:

Exercise: Clearly observe the syntax of each code and explain what is being done by given
code?

Control Flow Statement Examples


Syntax

If block if (x < 10)


disp(x); % only displays when x < 10
if (<condition>) end
<body> if ((0 < x) & (x < 100))
end disp('OK');
end
Code Explanation:

SIGNALS AND SYSTEMS LAB NUCES FAST, ISLAMABAD Page 5 of 19


Functions, Control Flow and Plotting in MATLAB LAB 3
If block if ((0 < x) & (x
if (<condition>) < 100))
<body> disp('OK'); else
else disp('x contains invalid
<body> number'); end
end
Code Explanation:

If block if (n <= 0)
if (<condition>) disp('n is negative or zero');
<body> elseif (rem(n,2)==0)
else if disp('n is
<body> even'); else
else disp('n is
<body> odd'); end
end
Code Explanation:

for block a = zeros(k,k) % Preallocate


matrix
for i = 1:1:10 for m = 1:k for n = 1:k
a(m,n) = 1/(m+n -1);
<body> end
end
end
Code Explanation:

SIGNALS AND SYSTEMS LAB NUCES FAST, ISLAMABAD Page 6 of 19


Functions, Control Flow and Plotting in MATLAB LAB 3
while block i=1;
while
while (i<=10)
(<condition>) disp(i);
i = i + 1;
end <body> end
Code Explanation:

switch statement method = 'bilinear';


switch<expression> switch lower(method)
case {'linear','bilinear'}
case <condition>, disp('Method is linear')
<statement> case 'cubic'
disp('Method is
otherwise cubic')
<condition>, otherwise
<statement> disp('Unknown
end method.') end

Code Explanation:

SIGNALS AND SYSTEMS LAB NUCES FAST, ISLAMABAD Page 7 of 19


Functions, Control Flow and Plotting in MATLAB LAB 3
PLOTTING

TWO-DIMENSIONAL plot() COMMAND

plot (x,y)

• where x is a vector (one dimensional array), and y is a vector. Both vectors must have the
same number of elements.

• The plot command creates a single curve with the x values on the abscissa (horizontal axis)
and the y values on the ordinate (vertical axis).

• The curve is made from segments of lines that connect the points that are defined by the x
and y coordinates of the elements in the two vectors.

PLOT OF GIVEN DATA:

x 1 2 3 5 7 7.5 8 10

y 2 6.5 7 7 5.5 4 6 8

• The code can be done in the Command Window, or by writing and then running a script
file.

Code to plot above data:

• Once the plot command is executed, the Figure Window must open with the following plot
as shown in “Fig 2.3”

SIGNALS AND SYSTEMS LAB NUCES FAST, ISLAMABAD Page 8 of 19


Functions, Control Flow and Plotting in MATLAB LAB 3

“Fig 2.3”

LINE SPECIFIERS IN THE plot() COMMAND:

Line specifiers can be added in the plot command to:


• Specify the style of the line.
• Specify the color of the line.
• Specify the type of the markers (if markers are desired).

plot(x,y,’line specifiers’)

The following tables lists the line specifiers:


Line Style Specifiers:

Specifier Line Style


- Solid line (default)
-- Dashed line
: Dotted line
-. Dash dot line

SIGNALS AND SYSTEMS LAB NUCES FAST, ISLAMABAD Page 9 of 19


Functions, Control Flow and Plotting in MATLAB LAB 3
Marker Specifier:

Specifier Marker Type


+ plus sign
O Circle
* Asterisk
. dot
s square
d diamond

Color Specifiers:

Specifier Line Color


r red
g green
b blue
c cyan
m magenta
y yellow
k black

• The specifiers are typed inside the plot() command as strings.

• Within the string the specifiers can be typed in any order.

• The specifiers are optional. This means that none, one, two, or all the three can be included
in a command.

Example:
• plot(x,y) A solid blue line connects the points with no markers.

• plot(x,y,’r’) A solid red line connects the points with no markers.

• plot(x,y,’--y’) A yellow dashed line connects the points.

• plot(x,y,’*’) The points are marked with * (no line between the points.)

• plot(x,y,’g:d’) A green dotted line connects the points which are marked with
diamond markers.

SIGNALS AND SYSTEMS LAB NUCES FAST, ISLAMABAD Page 10 of 19


Functions, Control Flow and Plotting in MATLAB LAB 3
Plot of given data using different line specifiers in the plot ( ) command. An example is shown in
Fig. 2.4.

Year 1988 1989 1990 1991 1992 1993 1994

Sales 127 130 136 145 158 178 211

“Fig 2.4”

Formatting the Plots:


A plot can be formatted to have a required appearance.

With formatting you can:


• Add title to the plot.
• Add labels to axes.
• Change range of the axes.
• Add legend.
• Add text blocks.
• Add grid.

SIGNALS AND SYSTEMS LAB NUCES FAST, ISLAMABAD Page 11 of 19


Functions, Control Flow and Plotting in MATLAB LAB 3
Formatting Commands:
title(‘string’)
Adds the string as a title at the top of the plot.

xlabel(‘string’)
Adds the string as a label to the x-axis.

ylabel(‘string’)
Adds the string as a label to the y-axis.

axis([xmin xmax ymin ymax])


Sets the minimum and maximum limits of the x- and y-axes.

legend(‘string1’,’string2’,’string3’)
Creates a legend using the strings to label various curves (when several curves are
in one plot). The location of the legend is specified by the mouse.

text(x,y,’string’)
Places the string (text) on the plot at coordinate x,y relative to the plot axes.

Example of Formatted Plot:

SIGNALS AND SYSTEMS LAB NUCES FAST, ISLAMABAD Page 12 of 19


Functions, Control Flow and Plotting in MATLAB LAB 3
x=[0:0.1:2*pi];
y=sin(x);
z=cos(x);
plot(x,y,x,z)
title('Sample Plot','fontsize',14);
xlabel('X values','fontsize',14);
ylabel('Y values','fontsize',14);
legend('Y data','Z data')
grid on

“Fig 2.5”

Displaying the Multiple Plots:

Three typical ways to display multiple curves in MATLAB (other combinations are possible…)
One figure contains one plot that contains multiple curves o Requires
the use of the command “hold” (see MATLAB help)

One figure contains multiple plots, each plot containing one curve o
Requires the use of the command “subplot”

Multiple figures, each containing one or more plots, each containing


one or more curves o Requires the use of the command “figure” and
possibly “subplot”

SIGNALS AND SYSTEMS LAB NUCES FAST, ISLAMABAD Page 13 of 19


Functions, Control Flow and Plotting in MATLAB LAB 3

One Plot Contains Multiple Curves:

Example:

x=[0:0.1:2*pi];
y=sin(x);
z=cos(x);
plot(x,y,x,z)
grid on

Or

x=[0:0.1:2*pi];
y=sin(x);
z=cos(x);
plot(x,y,’b’)
hold on
Plot(x,z,’g’)
hold off
grid on

• The plot figure produced by above code is shown in “Fig 2.5”.

Subplots:

• Subplot divides the current figure into rectangular panes that are numbered row wise.
• Syntax:

subplot(rows,cols,index)

SIGNALS AND SYSTEMS LAB NUCES FAST, ISLAMABAD Page 14 of 19


Functions, Control Flow and Plotting in MATLAB LAB 3
»subplot(2,2,1);
»…
»subplot(2,2,2)
» ...
»subplot(2,2,3)
» ...
»subplot(2,2,4)
» ...

“Fig 2.6”

Example of Subplot:
x=[0:0.1:2*pi];
y=sin(x);
z=cos(x);
subplot(1,2,1);
plot(x,y)
subplot(1,2,2)
plot(x,z)
grid on

“Fig 2.7”

SIGNALS AND SYSTEMS LAB NUCES FAST, ISLAMABAD Page 15 of 19


Functions, Control Flow and Plotting in MATLAB LAB 3
Multiple Figures:
Example:
x=[0:0.1:2*pi];
y=sin(x);
z=cos(x);
figure;
plot(x,y)
figure;
plot(x,z)
grid on

Debug a MATLAB Program


To debug your MATLAB® program graphically, use the Editor/Debugger. Alternatively, you can
use debugging functions in the Command Window. Both methods are interchangeable.
Before you begin debugging, make sure that your program is saved and that the program and any
files it calls exist on your search path or in the current folder.
• If you run a file with unsaved changes from within the Editor, then the file is automatically saved
before it runs.
• If you run a file with unsaved changes from the Command Window, then MATLAB software runs
the saved version of the file. Therefore, you do not see the results of your changes.
Set Breakpoint
Set breakpoints to pause the execution of a MATLAB file so you can examine the value or variables
where you think a problem could be. You can set breakpoints using the Editor, using functions in the
Command Window, or both.
There are three different types of breakpoints: standard, conditional, and error. To add
a standard breakpoint in the Editor, click the breakpoint alley at an executable line where you want
to set the breakpoint. The breakpoint alley is the narrow column on the left side of the Editor, to the
right of the line number. Executable lines are indicated by a dash ( — ) in the breakpoint alley. For
example, click the breakpoint alley next to line 2 in the code below to add a breakpoint at that line.

Run File
After setting breakpoints, run the file from the Command Window or the Editor. Running the file
produces these results:

SIGNALS AND SYSTEMS LAB NUCES FAST, ISLAMABAD Page 16 of 19


Functions, Control Flow and Plotting in MATLAB LAB 3
• Then press the Run.
• The prompt in the Command Window changes to K>> indicating that MATLAB is in debug mode
and that the keyboard is in control.
• MATLAB pauses at the first breakpoint in the program. In the Editor, a green arrow just to the right
of the breakpoint indicates the pause. The program does not execute the line where the pause occurs
until it resumes running. For example, here the debugger pauses before the program executes x =
ones(1,10);

• MATLAB displays the current workspace in the Function Call Stack, on the Editor tab in
the Debug section.
Pause a Running File
To pause the execution of a program while it is running, go to the Editor tab and click
the Pause button. MATLAB pauses execution at the next executable line, and the Pause button
changes to a Continue button. To continue execution, press the Continue button.
Pausing is useful if you want to check on the progress of a long running program to ensure that it is
running as expected.
Find and Fix a Problem
While your code is paused, you can view or change the values of variables, or you can modify the
code.
View or Change Variable While Debugging
View the value of a variable while debugging to see whether a line of code has produced the expected
result or not. To do this, position your mouse pointer to the left of the variable. The current value of
the variable appears in a data tip.

The data tip stays in view until you move the pointer. If you have trouble getting the data tip to
appear, click the line containing the variable, and then move the pointer next to the variable. For
more information, see Examine Values While Debugging.
You can change the value of a variable while debugging to see if the new value produces expected
results. With the program paused, assign a new value to the variable in the Command Window,
Workspace browser, or Variables Editor. Then, continue running or stepping through the program.
For example, here MATLAB is paused inside a for loop where n = 2:

SIGNALS AND SYSTEMS LAB NUCES FAST, ISLAMABAD Page 17 of 19


Functions, Control Flow and Plotting in MATLAB LAB 3

• Type n = 7; in the command line to change the current value of n from 2 to 7.


• Press Continue to run the next line of code.
MATLAB runs the code line x(n) = 2 * x(n-1); with n = 7.

EXERCISES:
Q1. Check the functionality of the following and write in your words what each command does in
MATLAB:
ceil()
floor()
round()
fix()
iseven()
isvector().
Isscalar().
Ischar().
audiowrite()
audioread()

Hint: Use Product help

Q2. Identify and explain the errors in the following codes.


a)
A= [1 2; 3 4];
C= [2 4]; B=A*C
_______________________________________________________________________________
_______________________________________________________________________________
_______________________________________________________________________________

b)
A= [1 2; 3 4];
C= [2 4]; B=C'*A

SIGNALS AND SYSTEMS LAB NUCES FAST, ISLAMABAD Page 18 of 19


Functions, Control Flow and Plotting in MATLAB LAB 3
_______________________________________________________________________________
_______________________________________________________________________________
_______________________________________________________________________________

c)
C= [2 4]; inv(C)
_______________________________________________________________________________
_______________________________________________________________________________
_______________________________________________________________________________

d)
x=-1:0.01:1;
y=0:0.1:1000;
plot(x,y)
_______________________________________________________________________________
_______________________________________________________________________________
_______________________________________________________________________________
a)
2x=4;
_______________________________________________________________________________
_______________________________________________________________________________
_______________________________________________________________________________

SIGNALS AND SYSTEMS LAB NUCES FAST, ISLAMABAD Page 19 of 19

You might also like