Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

ITCE436 Lab3 07

Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 9

University of Bahrain

College of IT
Department of CE

ITCE436 : Multimedia Communication

Lab3
Making a Movie, Simulating Sampling at Nyquist rate

1- 3D line plots
The command plot3 to plot lines in 3D is equivalent to the command plot in 2D. The
format is the same as for plot, it is, however, extended by an extra coordinate. An
example is plotting the curve is defined parametrically as r(t) = [t sin(t); t cos(t); t]
over the interval [-10 pi; 10 pi].

>> t = linspace(-10*pi,10*pi,200);
>> plot3(t.*sin(t), t.*cos(t), t, 'md-'); % plot the curve in magenta
>> title('Curve r(t) = [t sin(t), t cos(t), t]');
>> xlabel('x-axis'); ylabel('y-axis'); zlabel('z-axis');
>> grid

2- Control Flow
A control flow structure is a block of commands that allows conditional code
execution and making loops.

Logical and relational operators


To use control flow commands, it is necessary to perform operations that result in
logical values: TRUE or FALSE. In Matlab the result of a logical operation is 1 if it is
true and 0 if it is false. Table 1 shows the relational and logical operations. Another
way to get to know more about them is to type help relop. The relational operators <,
<=, >, >=, == and ~= can be used to compare two arrays of the same size or an
array to a scalar. The logical operators &, | and ~ allow for the logical combination or
negation of relational operators. In addition, three functions are also available: xor,
any and all (use help to find out more).
Table (1)

Important: The logical & and | have the equal precedence in Matlab, which means
that those operators associate from left to right. A common situation is:
>> b = 10;

1
>> 1 | b > 0 & 0
ans =
0
>> (1 | b > 0) & 0 % this indicates the same as above
ans =
0
>> 1 | (b > 0 & 0)
ans = 1

Conditional code execution


Selection control structures, if-blocks, are used to decide which instruction to execute
next depending whether expression is TRUE or not. The general description is given
below. In the examples below the command disp is frequently used. This command
displays on the screen the text between the quotes.

if ... end
Syntax
if logical_expression
statement1
statement2
....
end

Example
if (a > 0)
b = a;
disp ('a is positive');
end

if ... else ... end


Syntax
if logical_expression
block of statements
evaluated if TRUE
else
block of statements
evaluated if FALSE
end

Example
if (temperature > 100)
disp ('Above boiling.');
toohigh = 1;
else
disp ('Temperature is OK.');
toohigh = 0;
end

if ... elseif ... else ... end


Syntax
if logical_expression1
block of statements evaluated
if logical_expression1 is TRUE
elseif logical_expression2
block of statements evaluated

2
if logical_expression2 is TRUE
else
block of statements evaluated
if no other expression is TRUE
end

Example
if (height > 190)
disp ('very tall');
elseif (height > 170)
disp ('tall');
elseif (height < 150)
disp ('small');
else
disp ('average');
end

M-file:
To do the exercises below, a script m-file can be of use. It is an external _le that
contains a sequence of Matlab commands. What you need to do is to open an editor,
enter all commands needed for the solution of a task, save it with the extension '.m'
(e.g. mytask.m) and then run it from the Command Window, by typing mytask. To
open the Matlab editor, go to the File menu-bar, choose the Open option and then m-
file. A new window will appear where you can write your scripts and save them on the
disk. All commands in the script will be executed in Matlab. You will learn

Switch statement
Another selection structure is switch, which switches between several cases
depending on an expression, which is either a scalar or a string.

switch expression
case choice1
block of commands1
case {choice2a, choice2b,...}
block of commands2
...
otherwise
block of commands
end

Example
method = 2;
switch method
case {1,2}
disp('Method is linear.');
case 3
disp('Method is cubic.');
case 4
disp('Method is nearest.');
otherwise
disp('Unknown method.');
end

The statements following the first case where the expression matches the choice are
executed. This construction can be very handy to avoid long if .. elseif ... else ... end

3
constructions. The expression can be a scalar or a string. A scalar expression
matches a choice if expression == choice. A string expression matches a choice if
strcmp(expression, choice) returns 1 (is true) (strcmp compares two strings).

Important: Note that the switch-construction only allows the execution of one group
of commands.

3. Loops
Iteration control structures, loops, are used to repeat a block of statements until
some condition is met. Two types of loops exist:
- the for loop that repeats a group of statements a fixed number of times;

Syntax
for index = first:step:last
block of statements
end

Example
sumx = 0;
for i=1:length(x)
sumx = sumx + x(i);
end

You can specify any step, including a negative value. The index of the for-loop can be
also a vector. See some examples of possible variations:

Example 1
for i=1:2:n
...
end

Example 2
for i=n:-1:3
....
end

Example 3
for x=0:0.5:4
disp(x^2);
end

Example 4
for x=[25 9 81]
disp(sqrt(x));
end

- while loop, which evaluates a group of commands as long as expression is TRUE.

Syntax
while expression
statement1
statement2
statement3
...
end

4
Example
N = 100;
iter = 1;
msum = 0;
while iter <= N
msum = msum + iter;
iter = iter + 1;
end;

A simple example how to use the loop construct can be to draw graphs of f(x) =
cos(n x) for n = 1,…, 9 in different subplots. Execute the following script:

figure
hold on
x = linspace(0,2*pi);
for n=1:9
subplot(3,3,n);
y = cos(n*x);
plot(x,y);
axis tight
end
Given two vectors x and y, an example use of the loop construction is to
create a matrix A whose elements are
defined, e.g. as Aij = xi yj. Enter the following commands to a script:
n = length(x);
m = length(y);
for i=1:n
for j=1:m
A(i,j) = x(i) * y(j);
end
end

and create A for x = [1 2 -1 5 -7 2 4] and y = [3 1 -5 7]. Note that A is of size n-by-m.


The same problem can be solved by using the while-loop, as follows:

n = length(x);
m = length(y);
i = 1; j = 1; % initialize i and j
while i <= n
while j <= m
A(i,j) = x(i) * y(j);
j = j+1; % increment j; it does not happen automatically
end
i = i+1; % increment i
end

4- Script m-files
Matlab commands can be entered at the Matlab prompt. When a problem is more
complicated this becomes inefficient. A solution is using script m-_les. They are
useful when the number of commands increases or when you want to change values
of some variables and re-evaluate them quickly. Formally, a script is an external file
that contains a sequence of Matlab commands (statements). However, it is not a
function, since there are no input/output parameters and the script variables remain

5
in the workspace. So, when you run a script, the commands in it are executed as if
they have been entered through the keyboard.

Exercise
Create yourself a script: open the Matlab editor (go to the File menu-bar, choose the
Open option and then m-file; the Matlab Editor Window will appear), enter the lines
listed below and save as sinplot.m:

x = 0:0.2:6;
y = sin(x);
plot(x,y);
title('Plot of y = sin(x)');
and then run it by:
>> sinplot

The sinplot script affects the workspace. Check:


>> clear % all variables are removed from the workspace
>> who % no variables present
>> sinplot
>> who

Your variables are:


40
xy
_
These generic names, x and y, may be easily used in further computations and this
can cause side effects. Side effects occur in general when a set of commands change
variables other than the input arguments. Since scripts create and change variables
in the workspace (without warning), a bug, hard to track down, may easily appear.
So, it is important to remember that the commands within a script have access to all
variables in the workspace and all variables created in this script become a part of
the workspace. Therefore, it is better to use function m-files (see section 7.2), when
there is a specific problem to be solved.

Function m-file
Functions m-files are true subprograms, since they take input arguments and/or
return output parameters. They can call other functions, as well. Variables defined
and used inside a function, different from the input/output arguments, are invisible to
other functions and the command environment. The general syntax of a function is
presented below:

function [outputArgs] = function_name (inputArgs)

Matlab provides a structure for creating your own functions. The first line of the file
should be a definition of a new function (also called a header). After that, a
continuous sequence of comment lines should appear. Their goal is to explain what
the function does, especially when this is not trivial. Not only a general description,
but also the expected input parameters, returned output parameters and synopsis
should appear there. The comment lines (counted up to the first non-comment line)
are important since they are displayed in response to the help command. Finally, the
remainder of the function is called the body. Function m-files terminate execution
and return when they reached the end of the _le or, alternatively, when the
command return is encountered. As an example, the function average is defined as
follows:

6
Procedure:
1- Animations
A sequence of graphs can be put in motion in Matlab(the version should be at least
5.0), i.e. you can make a movie using Matlab graphics tools. To learn how to create a
movie, analyze first the script below which shows the plots of f(x) = sin(nx) over the
interval [0; 2pi] and = 1, … , 5:
N = 5;
M = moviein(N);
x = linspace (0,2*pi);
for n=1:N
plot (x,cos(n*x),'r-');
xlabel('x-axis')
if n > 1,
ss = strcat('cos(',num2str(n),'x)');
else
ss = 'cos(x)';
end
ylabel(ss)
title('Cosine functions cos(nx)','FontSize',12)
axis tight
grid
M(:,n) = getframe;
pause(1.8)
end
movie(M) % this plays a quick movie

Here, a for-loop construction has been used to create the movie frames. You will
learn more on loops in the next sections. Also the command strcat has been used to
concatenate strings. Use help to understand or learn more.
Play this movie to get acquainted. Five frames are first displayed and at the end, the
same frames are played again faster. Command moviein, with an integral parameter,
tells Matlab that a movie consisting of N frames is going to be created. Consecutive
frames are generated inside the loop. Via the command getframe each frame is
stored in the column of the matrix m. The command movie(M) plays the movie just
created and saved in columns of the matrix M. Note that to create a movie requires
quite some memory. It might be useful to clear M from the workspace later on.

2- Nyquist Sampling Rate


To plot a graph of a function, it is important to sample the function sufficiently well.
Compare the following examples:
Code1:
n = 5;
x = 0:1/n:3; % coarse sampling

7
y = sin(5*x);
plot(x,y)

Code 2:
n = 25;
x = 0:1/n:3; % good sampling
y = sin(5*x);
plot(x,y)

Analyze the two codes and comment on them

2- We deal with sampled discrete--time signals.


For a sampling frequency Fs, the discrete time increment is 1For a sampling
frequency Fs Hz, the discrete time increment is 1/Fs. For a signal duration of T
seconds, the number of samples is the number of samples is N = T*Fs, thus for a 1
second signal we get Fs samples.

For the discrete spectrum, it spans the range (0 – Fs) Hz. The usable part is (0 – Fs/2)
with (N/2+1) samples. The increment between discrete spectrum samples is 1/T Hz
(Thus the total range e is N*1/T = Fs).

clear;
%here we want to generate a sinewave with duration 0.1sec, sampling with duration
0.1sec,
frequency
%8000 Hz (sample per sec), and fundamental frequency 200Hz.
%In this case, del_t=1/8000, and the duration is 800 samples
Fs=8000;
for i=1:800
x1(i)=sin(2*pi*(i-1)/8000 * 200);
end
for i=1:800
tt(i)=(i-1)/8000;
end
for i=1:800
ff(i)=(i-1)/0.1;
end
figure(1);
subplot(2,1,1), stem (tt (1:200), x1(1:200));
subplot(2,1,2), plot (tt (1:200), x1(1:200));

Report:

1- Write a script that makes a movie consisting of 5 frames of the surface f(x; y) =
sin(nx) sin(ky) over the domain [0; 2pi] _ [0; 2pi] and n = 1 : 5. Add a title,
description of axes and shading.

2- Create a script which:


a. plots the function y = 2cos(x) at the range [-10; 10]. Choose a sufficient length for x
in order obtain a smooth plot.
b. plots the functions y = x2 and x = y2 in the same figure. Add a title, legend and
axes descriptions.
3- Modify the program at step (2) of the procedure by :
• adding the Fast Fourier Transform (FFT) for the signal x1(i)

8
• generating a square pulse instead of the sine wave

You might also like