ITCE436 Lab3 07
ITCE436 Lab3 07
ITCE436 Lab3 07
College of IT
Department of CE
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.
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
if ... end
Syntax
if logical_expression
statement1
statement2
....
end
Example
if (a > 0)
b = a;
disp ('a is positive');
end
Example
if (temperature > 100)
disp ('Above boiling.');
toohigh = 1;
else
disp ('Temperature is OK.');
toohigh = 0;
end
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
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
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
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:
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.
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)
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.
8
• generating a square pulse instead of the sine wave