0% found this document useful (0 votes)
18 views11 pages

Lab 1

Uploaded by

Mariam Ayman
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views11 pages

Lab 1

Uploaded by

Mariam Ayman
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

Basic Symbolic Matlab Functions

Function Operation
Calculus diff differentiate
int integrate
limit limit
taylor Taylor series
symsum summation
Simplification simplify simplify
expand expand
factor factor
simple find shortest form
subs symbolic substitution
Solving equations solve solve algebraic equations
dsolve solve differential equations
Transforms fourier Fourier transform
ifourier inverse Fourier transform
laplace Laplace transform
ilaplace inverse Laplace transform
ztrans Z-transform
iztrans inverse Z-transform
Symbolic operations sym create symbolic objects
syms create symbolic objects
pretty make pretty expression
Special functions dirac Dirac or delta function
heaviside unit-step function
Plotting ezplot function plotter
ezpolar polar coordinate plotter
ezcontour contour plotter
ezsurf surface plotter
ezmesh mesh (surface) plotter
Laboratory No. 1 Matlab and Signal Analysis

1 General Pointers

Throughout this and subsequent lab handouts, you’ll see boxes in the margins
that mean the following things:

Q0 A simple, single-right-answer question for you to answer in your write-up


D0 A more open-ended discussion question or series of questions for yo u to
address in your write-up

M0 Matlab signals or functions you need to create and show to your TA during
the lab

Your lab grade is affected by:

• The presentation quality of your write-up (to a small degree)

• Answers to the Q and D questions in the write-up

• Additional comments and observations you make in the write -up

• The signals and graphs you create and show to your TA during the lab

Each lab assignment is intended to take two weeks. The handouts are divided
into two parts, presented in separate sections, for your convenience. However,
they are to be handed in together.
2 Introduction to Matlab

If you are unfamiliar with Matlab, these websites might be helpful:

• http://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-
094-introductionto-matlab-january-iap-2010/lecture-notes/

• http://web.cecs.pdx.edu/ gerry/MATLAB/intro/intro.html

Google is also a fast way to find an answer.

2.1 Working directory

The working directory can be changed by clicking the ‘...’ button at the top of
the Matlab command window.

2.2 Matlab programming

Matlab is an industry standard software package for the analysis and


visualization of data. Much of its power lies in its highly optimized operations
on vectors and matrices. In many cases, you should be able to eliminate the for
loops you would need to write in C code with Matlab’s simple and fast
vectorized syntax.

Here’s a brief introduction:

• Help – Type help command name at the Matlab prompt to get help on a
specific command. For a nicer interface to the help utility, click the question
mark button at the top of the Matlab command window to get a separate help
window. If you don’t know the specific name of the command you’re looking
for, try using the look for command. You can also use the help command on
functions and scripts that you write yourself. The help command will always
output the comments under the function declaration or those at the top of the
script, so in order to have help work, you must always comment your functions
and scripts!
• Variable representation – All Matlab variables are vectors or matrices
(arrays) with double precision complex entries. You can create variables using
the = sign, e.g. v = [1 2 3].

• Operations on signals – The operators + and - operate how you would


expect in Matlab. However, be sure not to confuse the matrix multiplication
operator (*) with the element-by-element multiplication operator (.*). The
same applies to the matrix division and exponentiation operators ( /) and (ˆ )and
their element-by-element counterparts(./ )and( .ˆ). That is, if you have two
vectors x = [x(1), ... , x(5)] and y = [y(1), ... , y(5)], the command x.*y
produces the vector [x(1)*y(1), ... , x(5)*y(5)] and the command x*y produces
an error since these vectors can’t be matrix multiplied. Note that no for loops
are required for these element-by-element operations. The transpose operator(’)
swaps the dimensions of a matrix, so that a row vector becomes a column
vector and vice versa. All the normal elementary functions like cos and log are
in Matlab; see help elfun for a list.

• Other commands – For vectors, max(X) is the largest element in X. For


matrices, max(X) is a vector containing the maximum element from each
column. To get the maximum element of the entire matrix X, try max(X(:)).
Functions like min, mean, median, and abs can be used in a similar manner.

• Indexing – To create a vector that ranges from a to b in steps of 1, use v = a:b.


To specify a different step size step, use v = a:step:b. You can also use the colon

operator and the end keyword to get at the entries of vectors and matrices
easily. For example, to get every 5th element of the vector a, use a(1:5:end).
See help colon and help end.

• Elementary matrices – To help you create signals, you may find the
following commands useful:

– zeros(m,n) creates an m by n matrix of all zeros.

– ones(m,n) creates an m by n matrix of all ones.


– eye(n) creates an n by n identity matrix (ones down the diagonal, zeros
elsewhere.)

– rand(m,n) creates an m by n matrix of independent uniformly distributed


random variables between 0 and 1.

– randn(m,n) creates an m by n matrix of independent normally distributed


random variables with mean 0 and variance 1.

Also, the syntax c = [a,b] makes a new matrix c which is a and b put together
side-by-side (provided the vertical dimensions match). Using d = [a;b] makes a
new matrix d by putting a and b together top-to-bottom.

• Display – Use a semicolon ; at the end of a command to suppress the display


of results on the screen. Ctrl-C stops the execution of any command. You can
use the command whos to see the variables in your workspace and their sizes.
You can hit the up arrow key to get to previous commands, or type the first few
letters of a previous command and hit the up arrow to find the last matching
command. For example, typing p and pressing the up arrow brings back the last
command that started with the letter p.

• Viewing 1-D signals – Use the command plot(x) to plot a vector x. To plot a
vector y against a vector x (both must be the same size), use plot(x,y). You can
specify the color of the plot, the type of markers, and the line style; see help
plot for all the details. To plot several signals in the same window, type hold on
to prevent new plots from replacing the current plot. Use figure before any
visualizing commands such as plot and imagesc to bring up additional figures.

• Viewing 2-D signals – Use the command imagesc(M) to view the matrix M
as an image. The (1,1) entry of the matrix will be at the upper left hand corner.
You may need to use the command colormap gray to make the image more
understandable; large values are plotted as white, and small values are plotted
as black.
• Listing to sound signals – Use the command sound(x,Fs) to send the signal x
with sample frequency Fs to the computer sound system. A similar command,
soundsc(x,Fs), will first rescale the signal to give maximum volume without
clipping. You can also write and read .wav files using wavread and wavwrite.

• Saving and loading – Matlab data can be stored into binary .mat files on your
disk. To save your whole workspace in a file called filename.mat use save
filename. To save one particular variable called variable name into
filename.mat type save filename variable name. Saving will overwrite
whatever filename you specify. To append instead of overwrite, use save
filename variable name -append. Note that the saved files are in a special
format, and are unreadable by other applications. You can use save ... -ascii" to
save your workspace as a text file. See help save for more details. Load a .mat
file by typing load filename. Again, you can load only specific variables using
load filename variable name. See help load for more details. • Writing Matlab
programs – Procedures that you call repeatedly can be stored either as functions
or as macros. You create both of these by writing a .m file in a text editor and
storing it in your working directory. Macros operate on existing variables in
your workspace (i.e., change them, modify them, create new ones, etc.). They
do not have to be passed any inputs. You run them by typing macro name while
running Matlab. Functions operate only on variables passed to them and they
do not change the existing workspace. The headers of their .m files have to
include a statement like: function [out1, ... outN] = function name(input1,
input2,.., inputN) The final value of variables out1, ... , outN will be
automatically returned, once the function execution is finished. User created
functions are called in the same manner as built-in functions.

2.3 Matlab examples We will be working with samples of continuous -time


signals. Let x(t),t ∈ [0,T], be a continuous-time signal defined over the time
interval [0,T]. Fix an integer N > 1 and set ∆ = T/N. Then provided N is
sufficiently large the signal x can be adequately represented by the set of N

uniformly spaced samples s(k) = x(tk) where tk = k∆, k = 0,1,...,N −1. The
sampling frequency in the above representation is Fs = 1/∆ = N/T. Roughly,
Nyquist sampling theorem says that if the sample frequency is more than twice
the highest frequency present in the signal, then the samp les accurately
represent the original signal. (We will do more on this later.) A sampled signal
can be stored as the elements of a 1 × N matrix.

For example, the signal x(t) =sin(2 t),t ∈ [0,10], can be represented in Matlab
as a 1×N matrix as follows:

Ts = 0.1;
N = 100;
t = [0:N-1]*Ts;
x = sin(2*t);

Here, Ts is the inter-sample time ∆ (So 1/Ts is the sample frequency); N is the
total number of samples; t is a 1×N matrix indexed from 1 to N containing the
sample times 0, Ts, 2Ts, ... (N-1)Ts; x is a 1×N matrix containing the samples
of the signal sin(2t) at the sample times.

2.3.1 Plotting a signal

You can plot the signal with the commands:

plot(t,x);
grid
xlabel('time – secs')
ylabel('signal x')
title('Plot of x vs t')

You can also use the plot command to plot several signals on the same graph
and you can control the colors of the lines as well as their type. For example,

y = 2*x;
plot(t,x,’-’,t,y,’--’);
grid
xlabel('time – secs')
ylabel('signal x')
title('Plot of x and y vs t')
will plot the signals x and y on the same graph. The first signal will be plotted
with a solid line and the second signal will be plotted in a dashed line. Use the
help facility to learn all the color and line type controls. Sometimes you may
want to plot more than one signal on the same page but on different graphs. In
this case you can use the subplot command to set up an array of plots. For
example,

subplot(2,1,1), plot(t,x,'g');
grid
xlabel('time – secs')
ylabel('signal x')
title('Plots of x and y')
subplot(2,1,2), plot(t,y,'r');
grid
xlabel('time – secs')
ylabel('signal x')

will plot the signals x and y on a 2 by 1 grid of separate plots. The first signal
will be plotted in a green line and the second in a red line. You can also plot
each group of signals on a completely new page using the figure command. For
example,

figure (1)
plot(t,x);
grid
xlabel('time – secs')
ylabel('signal x')
figure(2) plot(t,y);
grid
xlabel('time – secs')
ylabel('signal y')

will plot the signal x on the first figure window and the signal y on the second
figure window.

2.3.2 Writing an m-file


Usually the best way to use Matlab is to first write a Matlab program, called an
m-file. You can create scripts and functions this way. Scripts allow you to
make changes, fix bugs, etc., in an efficient manner, without having to retype a
bunch of commands. To write an m-file you use any text editor to create a file
containing Matlab commands and store the file as ASCII with a .m extension.
Matlab also has a built in editor for this purpose. The m-files need to be stored
in the working directory or path. The m-file is executed by calling the name of
the file (without the .m extension). A script is the simplest program you can
write in Matlab. It is an automated sequence of Matlab commands. When it is
executed, it is as if you typed all of those commands in order. A script might
look like this:

clear % clear memory


clf reset % clear all figures
T = 10; % signal duration
Fs = 8000; % sampling frequency
f = 440; % frequency of sound
t = 0:1/Fs:T; % time axis
n = T*Fs; % length of vector
x = 4 * exp(-2*t).*sin(2*pi*f*t);
plot(t(1:n),x(1:n),’r’)
grid
xlabel('time-secs')
ylabel('signal value – volts')
title('A Plot of a Simple Signal')
sound(x,Fs) % play the signal
Notice that if Matlab encounters a % symbol on any input line it ignores the
rest of that line. So the % symbol can be used to add comments to your
programs. To run a script file, just type the name of the file into the command
line. Values such as T, Fs, t, and x will become workspace variables in your
environment after running the script.

2.3.3 Functions

The m-file must start with the word function and state the inputs and outputs. A
simple function program might look like this:

function x = myFunction(Fs, f)
% function x = myFunction(Fs, f)
% Fs is the sampling frequency
% f is the frequency of sound
% x is the sound signal
T = 10; % signal duration
t = 0:1/Fs:T; % time axis
n = T*Fs; % length of vector
x = 4 * exp(-2*t).*sin(2*pi*f*t);
plot(t(1:n),x(1:n),’r’)
grid
xlabel('time-secs')
ylabel('signal value – volts')
title('A Plot of a Simple Signal')

To run this function with Fs = 8000 and f = 440, type the following into the
command line:

>> output = myFunction(8000, 440);

If instead you want to write myFunction so that it returns more than one
variable, enclose all your output variables with square brackets:

function [x, t] = myFunction(Fs, f)

To run this in your command line, you can type:

>> [output1, output2] = myFunction(8000, 440);

3 Lab Procedure—Part 1

This section of the handout needs to be completed and handed in.

The goals of this lab are the following:

• Familiarize yourself with the Matlab environment


• Learn how to write Matlab programs
• Create and manipulate one- and two-dimensional signals
• Get a feel for the effects of frequency content, sampling rate, and noise
on the sound of a signal

• Simple 1-D signals

To get some practice in creating signals, generate and plot the following
variables. All of the variables should be row vectors.

1. twos, a vector 50 elements long where every element is 2

2. ramp1, a vector that goes from 5 to 55 in steps of 1

3. ramp2, a vector that goes from 23 to 18 in steps of -.1

4. rampprod, the element-by-element product of ramp1 and ramp2 M1

5. oto4pi, a vector that goes from 0 to 4π in steps of .01. (Use the built -in
variable pi)

6. cos1, the function f(t) = acos(2πνt+b), where a is 3, ν is 0.7, b is 0.3, and t


ranges from 0 to 4π. (Use the variable oto4pi above) M2

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy