Docsity

DSP Laboratory Digital Signal Processing, Lecture notes of Digital Signal Processing

Toggle sidebar
bg1
ELEG-212 Signals and Communications
1/7
Lab 0: Introduction to MATLAB
1 Overview
MATLAB is a technical computing environment for high-performance numeric computation and
visualization. MATLAB integrates numerical analysis, matrix computation, signal processing,
and graphics into one easy-to-use compiler-less environment. Unlike traditional programming
languages such as Fortran and C, MATLAB is optimized for vector and matrix operations. In
fact, the name MATLAB stands for matrix laboratory.
MATLAB has a rich family of application-specific solution packages called toolboxes, which are
comprehensive collections of MATLAB functions related to particular problems. MATLAB
version 6.1 has more than 16 toolboxes including the Signal Processing Toolbox, Statistics
Toolbox and Communications Toolbox. Except for some built-in functions, MATLAB is an open
source software package. Thus you can not only directly apply the built-in and toolbox functions,
but also learn to use MATLAB more efficiently by examining the code for these functions and
modifying it to fit specific tasks and applications. This is a key feature that has led to the
widespread use of MATLAB.
The specific objectives of this lab include:
1. Learning to use the help system to study basic MATLAB commands and syntax.
2. Writing your own functions and m-file's in MATLAB.
3. Learning some advanced programming techniques for MATLAB, i.e., vectorization.
Before undertaking the following tasks, please make sure that you have read the MATLAB
overview in the Signal Processing First book. Numerous other MATLAB primers are available on
the Internet. A list of commonly used commands is given in the appendix of this document. You
should also make use of the help command within MATLAB. Utilizing help function
gives specific help on the given command.
2 Procedures
2.1 Basic Commands
The following exercises will begin your orientation in MATLAB.
(a) View the MATLAB introduction by typing intro at the MATLAB prompt. This short
introduction will demonstrate some of the basics of using MATLAB.
(b) Explore the MATLAB help capability. Type each of the following lines to read about
these commands:
help
help plot
help colon
help ops
help zeros
help ones
lookfor filter %<--- keyword search
If the lines scroll past the bottom of the screen, it is possible to force MATLAB to display
only one screen-full of information at a time by issuing the command more on.
(c) Use MATLAB as a calculator. Try the following:
pi*pi - 10
pf3
pf4
pf5

Partial preview of the text

Download DSP Laboratory Digital Signal Processing and more Lecture notes Digital Signal Processing in PDF only on Docsity!

Lab 0: Introduction to MATLAB

1 Overview

MATLAB is a technical computing environment for high-performance numeric computation and visualization. MATLAB integrates numerical analysis, matrix computation, signal processing, and graphics into one easy-to-use compiler-less environment. Unlike traditional programming languages such as Fortran and C, MATLAB is optimized for vector and matrix operations. In fact, the name MATLAB stands for matrix laboratory.

MATLAB has a rich family of application-specific solution packages called toolboxes , which are comprehensive collections of MATLAB functions related to particular problems. MATLAB version 6.1 has more than 16 toolboxes including the Signal Processing Toolbox, Statistics Toolbox and Communications Toolbox. Except for some built-in functions, MATLAB is an open source software package. Thus you can not only directly apply the built-in and toolbox functions, but also learn to use MATLAB more efficiently by examining the code for these functions and modifying it to fit specific tasks and applications. This is a key feature that has led to the widespread use of MATLAB.

The specific objectives of this lab include:

  1. Learning to use the help system to study basic MATLAB commands and syntax.
  2. Writing your own functions and m-file's in MATLAB.
  3. Learning some advanced programming techniques for MATLAB, i.e., vectorization.

Before undertaking the following tasks, please make sure that you have read the MATLAB overview in the Signal Processing First book. Numerous other MATLAB primers are available on the Internet. A list of commonly used commands is given in the appendix of this document. You should also make use of the help command within MATLAB. Utilizing help function gives specific help on the given command.

2 Procedures

2.1 Basic Commands

The following exercises will begin your orientation in MATLAB. (a) View the MATLAB introduction by typing intro at the MATLAB prompt. This short introduction will demonstrate some of the basics of using MATLAB. (b) Explore the MATLAB help capability. Type each of the following lines to read about these commands: help help plot help colon help ops help zeros help ones lookfor filter %<--- keyword search If the lines scroll past the bottom of the screen, it is possible to force MATLAB to display only one screen-full of information at a time by issuing the command more on. (c) Use MATLAB as a calculator. Try the following: pi*pi - 10

sin(pi/4) ans ^ 2 %<--- "ans" holds the last result (d) Variable names can store values and matrices in MATLAB. Try the following: xx = sin( pi/5 ); cos( pi/5 ) %<--- assigned to what? yy = sqrt( 1 - xxxx ) ans (e) Complex numbers are natural in MATLAB. Notice that the names of some basic operations are unexpected, e.g., abs for magnitude. Try the following: zz = 3 + 4i conj(zz) abs(zz) angle(zz) real(zz) imag(zz) help zprint %- requires DSP First Toolbox exp( sqrt(-1)pi ) exp(j[ pi/4 -pi/4 ]) (f) Plotting is easy in MATLAB, for both real and complex numbers. The basic plot command will plot a vector yy versus a vector xx. Try the following: xx = [-3 -1 0 1 3 ]; yy = xx.xx - 3xx; plot( xx, yy ) zz = xx + yysqrt(-1); plot( zz ) %<---- complex values can be plotted Drop the semicolons, if you want to display the values in the x, y, and z vectors. Use help arith to learn how the operation xx.*xx works; compare to matrix multiply.

When unsure about a command, use help.

2.2 MATLAB Array Indexing

(a) Make sure that you understand the colon notation. In particular, explain what the following MATLAB code will produce jkl = 2 : 4 : 17 jkl = 99 : -1 : 88 ttt = 2 : (1/9) : 4 tpi = pi * [ 2 : (-1/9) : 0 ] (b) Extracting and/or inserting numbers in a vector is very easy to do. Consider the following definition: xx = [ ones(1,4), [2:2:11], zeros(1,3) ] xx(3:7) length(xx) xx(2:2:length(xx)) Explain the result echoed from the last three lines of the above code. (c) In the previous part, the vector x contains 12 elements. Observe the result of the following assignment: xx(3:7) = pi*(1:5) Now write a statement that will replace the odd-indexed elements of xx with the constant -77 (i.e., xx(1), xx(3), etc). Use a vector indexing and vector replacement.

The following lines of code should be saved in a file called mysound.m and run from the command line. dur = 1.0; fs = 8000; tt = 0 : (1/fs) : dur; xx = sin( 2pi2000*tt ); sound( xx, fs ) The sound hardware will convert the vector of numbers xx into a sound waveform at a certain rate, called the sampling rate. In this case, the sampling rate is 8000 samples/second, but other values might be used depending on the capability of sound hardware. What is the length of the vector xx? Read the online help for sound (or soundsc) to get more information on using this command.

2.6 Functions

The following warm-up exercises are to help you in writing functions in MATLAB. Although these examples contain minor errors, they do exemplify the correct structure and syntax for writing functions. (a) Find the mistake in the following function: function xx = cosgen(f,dur) %COSGEN Function to generate a cosine wave % usage: % xx = cosgen(f,dur) % f = desired frequency % dur = duration of the waveform in seconds % tt = [0:1/(20f):dur]; % gives 20 samples per period yy = cos(2piftt); (b) Find the mistake in the following function: function [sum,prod] = sumprod(x1,x2) %SUMPROD Function to add and multiply two complex %numbers % usage: % [sum,prod] = sumprod(x1,x2) % x1 = a complex number % x2 = another complex number % sum = sum of x1 and x % prod = product of x1 and x % sum = z1+z2; prod = z1*z2; (c) Explain the following lines of MATLAB code: yy = ones(7,1) * rand(1,4); xx = randn(1,3); yy = xx(ones(6,1),:); (d) Write a function that performs the same task as the following without using a for loop. Consult the matrix multiplication section in the appendix on Using MATLAB for some clever solutions. function Z = expand(xx,ncol) %EXPAND Function to generate a matrix Z with identical %columns equal to an input vector xx % usage: % Z = expand(xx,ncol) % xx = the input vector containing one

% column for Z % ncol = the number of desired columns % xx = xx(:); %-- makes the input vector x into a %column vector Z = zeros(length(xx),ncol); for i=1:ncol Z(:,i) = xx; end

2.7 Vectorization

(a) Explain the following lines of MATLAB code: A = randn(6,3); A = A .* (A>0); (b) Write a new function that performs the same task as the following function without using a for loop. Use the idea in part (a) and also consult section on vector logicals in the Using MATLAB section of the appendix. In addition, the MATLAB logical operators are summarized via help relop. function Z = replacez(A) %REPLACEZ Function that replaces the negative elements % of a matrix with the number 77 % usage: % Z = replacez(A) % A = input matrix whose negative elements % are to be replaced with 77 % [M,N] = size(A); for i=1:M for j=1:N if A(i,j) < 0 Z(i,j) = 77; else Z(i,j) = A(i,j); end end end

2.8 Exercises: Using MATLAB

The following exercise can be completed at your convenience. Results from each part should be included in a brief lab report write-up.

2.8.1 Manipulating Sinusoids with MATLAB

Generate two 3000 hertz sinusoids with different amplitudes and phases. x 1 (t) = A 1 cos(2ฯ€(3000)t + ฯ† 1 ) x 2 (t) = A 2 cos(2ฯ€(3000)t + ฯ† 2 ) (a) Select the value of the amplitudes as follows: let A 1 = 13 and use your age for A 2. For the phases, use the last two digits of your telephone number for ฯ† 1 (in degrees), and take ฯ† 2 = 30ยฐ. When doing computations in MATLAB, make sure to convert degrees to radians. (b) Make a plot of both signals over a range of t that will exhibit approximately 3 cycles. Make sure the plot starts at a negative time so that it will include t = 0, and make sure that your have at least 20 samples per period of the wave. (c) Verify that the phase of the two signals x 1 (t) and x 2 (t) is correct at t = 0, and also verify that each one has the correct maximum amplitude.

4 Appendix: Commonly used MATLAB Commands

help โ€“ online documentation demo โ€“ run GUI demos which โ€“ locate functions or m-files lookfor โ€“ keyword search

Workspace Management: clear โ€“ clear memory space whos โ€“ list all variables in memory save โ€“ save current workspace variables (.mat format) load โ€“ load workspace from file

Operators: ; โ€“ suppress the result display % โ€“ comment == โ€“ equality, โ€œ=โ€ is assignment โ€ฆ โ€“ input line continuation .* ./ .^ โ€“ array operations, element-by-element .โ€™ โ€“ non-conjugated transpose, โ€œ โ€™ โ€ is conjugated transpose ! โ€“ execute OS command, ex: !cp : โ€“ array indexing, ex: 0:0.1:1, N:-1:1, A(:, j:k) note: Linspace can control the number of the array exp โ€“ raise e to the power sqrt โ€“ square root

Matrix Basics: length โ€“ length of array, return an integer size โ€“ size of matrix, return an array zeros โ€“ zeros matrix ones โ€“ ones matrix eye โ€“ identity matrix rand โ€“ matrix of uniformly distributed random variables randn โ€“ matrix of normally distributed random variables

Complex Basics: conj โ€“ complex conjugate abs โ€“ magnitude real โ€“ real part imag โ€“ imaginary part

Graphics: figure โ€“ create or specify a graphics window plot โ€“ 2-D linear plot, ex: plot(x, y1, โ€˜-bโ€™, x, y2, โ€˜:rโ€™) stem โ€“ plot discrete signals. ex: stem(n,x,'fill') subplot โ€“ create more plots in one figure semilogx โ€“ semi-log plot on x-axis, also see semilogy and loglog title โ€“ plotโ€™s title xlabel โ€“ label of x axis, ylabel is for y axis axis โ€“ ex: axis([0 100 0 1]), axis on/off legend โ€“ ex: legend(โ€˜Gaussionโ€™, โ€˜Laplacianโ€™, 0); grid โ€“ ex: grid on/off;

pre-defined variables: eps, (i or j), pi, inf, NaN