MATLAB Structure and Use: 1.1 Pre-Lab Assignment
MATLAB Structure and Use: 1.1 Pre-Lab Assignment
where:
=
1.5 3.3
6 4.5
2.5 0.7
, 1 =
0.5 0.3
0.1 0.2
0.4 0.3
C =
[
1 2
1 2
]
, 1 =
[
3.1 1.4 0.3
0.5 1.6 0.1
]
6 CHAPTER 1. MATLAB STRUCTURE AND USE
3. We dene the element of matrix o in row i and column , as o
d
4
for all i and , for your choice of three 2x3 arrays /, c, and d. Manually verify the
result for i = 1 and , = 2.
1.3.5 Function m-Files
The input-output characteristics of a script m-le make it very impractical to use as a subroutine
within a program. Function m-les are useful for this purpose since they can be created with
input and/or output variables. No variables remain in the Workspace after a function m-le has
completed. As such, data must be passed back out or saved with a save statement within the
function if it is to be used again.
1. Read (but not necessarily reproduce) Section A.1.3.
2. Create a function called sumsin that sums two sinusoids. The inputs should be t, f1, f2.
The outputs should be :
1
= sin(2)
1
t), :
2
= sin(2)
2
t), and :
3
= :
1
+:
2
.
To test your function you may wish to call it in the Command Window. To do this, dene two
frequencies and an appropriate time span and issue the command
[s1 s2 s3] = sumsin(t,f1,f2);
If there are no errors, you may assume that your function works correctly.
1.3.6 Logical Operators
1. Reproduce the logical operator examples in Section A.2.2.
2. In a script m-le, use logical and array operations to produce / from o where
o =
1.2 3.2 24
0.6 0.3 0.5
2.3 1.6 20
and / =
1.2 0 0
0 0.6 1
0 1.6 0
2
1.6
+ 3
0.5
4. If t varies from 1.2 to 1.2 in steps of 0.4, nd:
(a) n(t) = 3t
3
+ 2t
2
t + sin t
(b) r(t) =
{
0, t < 0
2, t 0
1.3. LABORATORY PROCEDURE 7
1.3.8 Flow Control Statements
1. Reproduce the examples in Section A.3.
2. Use for statements to nd the values of r(t) = 3 cos(2)t + 0.1) for t = 0, 0.1, 0.2, and 0.4
seconds when ) = 10, 15, and 20 Hz. Use one set of statements to compute the values for all
three frequencies and store the results in a two-dimensional array. (Hint: use nested loops.)
What is the value when r(0.3) when ) = 15 Hz?
3. Use while statements to nd the largest value of positive t for which c
1.2
cos(.t) and t
3
are
both less than 10. Make the computation for . {35, 40, 45} and nd the solution to the
nearest 0.01.
4. Evaluate r(t) = c
1 0 2 3 0 4
4 0 3 2 0 1
1 2 3 4 0 0
1 4 3 2
4 1 2 5
3 3 5 1
0
r(:)d:. Also, in the same gure, the function should
output graphs of the function, its derivative, and its integral on separate axes. These plots should
be labeled nicely.
Kane Warriors rst line in his script would look like this:
function [xdot integ] = WarriorKLab1(x,deltat)
Of course Kane would be encouraged to write a short introduction or help section for his function.
Appendix A
MATLAB Overview
This appendix provides a broad overview of a few choice features of MATLAB. It should be pointed
out, however, that MATLAB is both a programming language as well as a software suite. Thus it
is just as appropriate to refer to MATLAB code as to open MATLAB.
The choice of which features to include here primarily results from their usefulness in the 351L
laboratory. Deeper help on these topics as well as the myriad of other functions in MATLAB can
be obtained from a number of outside references, including those in the bibliography.
A.1 Basic MATLAB Interface
The MATLAB desktop consists of four basic windows:
Command Window
Command History
Current Directory
Workspace
A fth important windowthe Editorcan be opened by typing edit at the command prompt
(). When running experiments with many windows open, it is sometimes helpful to dock the
Editor into the MATLAB desktop. The Editor window has an icon similar to that can be used
to dock it with the main MATLAB desktop.
The Command Window is useful for executing les or making quick calculations. Lengthy
processes are better suited to be written in a scriptmore on that later. The Command Window
may be cleared by issuing the command clc.
The Command History logs all of the actions executed in the Command Window as well as
sign-in and exit times from MATLAB. It is most useful for nding commands issued previously if
there is a lot of output cluttering the Command Window. Also, you may select several lines from
the command history and drag them into the Editor if you wish to save them into a script.
The Current Directory is familiar to Windows users. It should be noted, however, that MATLAB
can only execute scripts from the Current Directory (and subdirectories) and the MATLAB root
directory. Thus if you wrote code for Lab 1 and wanted to run it in your Lab 2 directory, it would
be easiest to copy-paste the le.
The Workspace lists all of the variables (and their type) that are currently active. To clear the
Workspace, use the command clear all. To delete a certain variable (call it var), use clear var.
Also note that clearing the Command Window does not clear the Workspace and vice-versa.
33
34 APPENDIX A. MATLAB OVERVIEW
A.1.1 Statements
Statements are entered in the Command Window at the command prompt: . The comment
symbol in MATLAB is the percent sign: %. When MATLAB encounters this symbol, it ignores
the remaining text on that line. Comments are useful for creating headers for scripts. It is
recommended that you include some authorship information in every script you write.
Example Code:
>> % Kane Warrior
>> % Lab 1, Section 2
>> % Data Analysis and Plotting Script
>> % 17 July 2008
Results from statements issued are by default stored in the single variable named ans. This
variable will show up in the Workspace and appear in the Command Window:
Example Code:
>> 3.45 <Enter>
ans =
3.4500
>>
Pressing the Enter key causes MATLAB to execute the statement in the command prompt.
Example Code:
>> sqrt(1.44) <Enter>
ans =
1.2000
>>
If a statement is too long for a single line, one may issue a carriage return by typing three
periods (...) and then the Enter key.
Example Code:
>> 2 + 6.35 + sqrt(36) ... <Enter>
+ sqrt(49) <Enter>
ans =
21.3500
>>
Note: From now on the explicit typing of <Enter> will be assumed to be understood and therefore
omitted.
Multiple statements may be issued on one line by separating them with a comma. The state-
ments are executed from left to right.
Example Code:
>> clear all
>> 5, ans + 1.1
ans =
A.1. BASIC MATLAB INTERFACE 35
6.1000
>>
Variables are user-dened entities that allow the saving and recalling of information throughout a
MATLAB session. Variables may be named according to certain conventions, the most important of
which is that they must begin with a letter. All variables currently active appear in the Workspace.
A quick list of all of the variable names can be produced in the Command Window with the who
command. A more complete table with variable names, dimensions, sizes, and classes is obtained
by using the plural form: whos.
Statements that are terminated with a semicolon (;) are executed, but the results are not shown
in the Command Window. Any variables assigned are saved and may be displayed by typing that
variables name subsequently:
Example Code:
>> a = 25; b = sqrt(a) + 2.5;
>>
>> a, b
a =
25
b =
7.5000
>>
A.1.2 Help
MATLABs biggest advantage over other programming languages is its library of functions. To aid
users in nding a function, MATLAB has two very useful commands.
To see a list of functions that have a certain word in the title or description, use the lookfor
command.
Example Code:
>> lookfor sinc
DIRIC Dirichlet, or periodic sinc function
SINC Sin(pi*x)/(pi*x) function.
INVSINC Desired amplitude and frequency response for invsinc
filters
>>
To get explicit information on a single function whose name is known, the help function is
extremely useful. It explains the syntax and purpose of every function in the MATLAB library.
Example Code:
>> help sqrt
SQRT Square root.
SQRT(X) is the square root of the elements of X. Complex
results are produced if X is not positive.
See also sqrtm.
>>
36 APPENDIX A. MATLAB OVERVIEW
A.1.3 M-Files
Files with extension .m are executable in MATLAB. There are two avors of m-les: Script and
Function. All m-les contain plain text, and as such can be edited with any text editor. MATLAB
provides a customized text editor, as discussed above. However, you may read, write, and edit
m-les with any plain text editor (such as Notepad, WinEdt, emacs, etc.).
Scripts
Scripts are helpful because they can lump dozens or even thousands of Command Line statements
into a single action. The conventions for naming scripts are very similar to those for naming
variables:
Do Not begin lenames with numbers
Do Not include punctuation anywhere in lenames
Do Not use a lename that is already used for a MATLAB function or an existing variable
There are a few useful shortcut keys when writing and debugging scripts. The F5 key saves and
executes the entire active script. When dealing with long les, it is often useful to execute only the
code you have just written. The F9 key executes only the text that is currently highlighted.
Functions
There are thousands of functions in the MATLAB library. However, one may nd it necessary to
write a new functionoften a collection of other functionsto suit ones specic needs. Just like
MATLAB native functions, user-dened functions have a strict yet simple syntax. To dene a new
function, there are four essential components that must be the rst executable line in the m-le:
The MATLAB command function
Output variables
The user-dened function name
Input variables
Output variables are contained in [square brackets] and separated by commas. Input variables
are contained in (parentheses) and also separated by commas. Comments may appear above the
line containing the function command, and these will appear when the help command is issued
in relation to this new function.
Example Code:
% Kane Warrior
% 17 July 2008
%
% VECTOR function
% INPUTS:
% x A complex number
%
% OUTPUTS:
% m Magnitude of x
% theta Angle of x in degrees counterclockwise from positive
% Real axis
%
A.1. BASIC MATLAB INTERFACE 37
function [m,theta] = vector(x)
m=abs(x); %Use the native function abs.
theta=angle(x)*180/pi; %Use the native function angle and
% convert from radians to
% degrees.
A.1.4 Storage and Retrieval Commands
Data can be stored as variables, which can then be saved to memory. The syntax is:
save filename <variables> . This saves the variables listed in <variables> separated by
spacesas a le called filename.mat in the current directory. If no variables are specied, all
of the variables in the Workspace are saved.
Upon clearing the Workspace, the variables can be restored by issuing load filename . This will
restore the variables saved in filename.mat to the workspace and overwrite any existing variables
with the same name.
A.1.5 Numeric Format
There are several types of numbers recognized by MATLAB. So far we have only dealt with ratio-
nals. We will, however, need more general numbers (such as non-repeating decimals and complex
numbers).
The default setting in MATLAB is for numbers to be truncated after four digits to the right
of the decimal and nine to the left. After this, the number will be presented in scientic notation.
If this is not convenient, the command format long will always give 15 digits to the right of the
decimal. To revert, use format short.
Floating Point Numbers
Floating point numbers represent real numbers. They are how computers interpret what we know
as 2, 1,2, and log 2. Floating point numbers come in various precisions, the most common of which
are single and double. The default for MATLAB is double precision. This should not become an
issue in this course, so we will leave it at that.
As an example, let us issue the following commands:
Example Code:
>> s = 0.5555;
>> l = 0.55555
l =
0.5555
>> format long
>> s - l
ans =
-4.999999999999449e-005
Complex Numbers
One feature that sets MATLAB apart from other languages is how it deals with complex numbers.
Upon startup, the variables i and j are predened to both be
1. Say, for example, that on lines 1020 in a script there is a for loop that
uses i as its index and runs up to i = 100. Then on line 25, the script tries to execute complex
variable assignment x = 4+5*i;. Of course, unless the variable i was cleared between lines 20 and
25, the script will create x = 504 and not the desired x = 4.0000 + 5.0000*i. The moral is to
be very careful when using i and j as non-native variables.
Arrays
Arrays are the heart and soul of MATLAB (MATrix LABoratory). Arrays are groups of numbers
that travel around together. They may be grouped so they stay in the right order, so that they
perform some mathematical operation, or any other reason. We are all familiar with one- and two-
dimensional arrays. We already know them as vectors and matrices, respectively. However, MAT-
LAB can handle higher-dimensional arrays; for these it is easier to think of every two-dimensional
object as being a matrix stacked among others.
Arrays are dened using square brackets: [ ]. Entries in a row may be separated by either a
comma or whitespace (space bar). A row is terminated and a new one begun with either a semicolon
or a line break within the brackets.
A.1. BASIC MATLAB INTERFACE 39
Example Code:
>> rvec = [1 2 3 4]
rvec =
1 2 3 4
>> cvec = [11; 12; 13; 14]
cvec =
11
12
13
14
>> TwoDimArray = [1 2 3
4 5 6
7, 8, 9]
TwoDimArray =
1 2 3
4 5 6
7 8 9
In MATLAB, array dimensions are always listed with rows rst and columns second. For
example, if we wanted to call out the 6 from the variable TwoDimArray, we would enter
Example Code:
>> TwoDimArray(2,3)
ans =
6
This is because the 6 lies in the second row and the third column. Some helpful array creation and
basic modication commands are listed in Table A.2.
We can also make an array by concatenating smaller arrays. Special attention must be paid to
the dimensions in order to make a valid concatenation.
Example Code:
>> h = [1 2 3], k = [4; 7], m = [5 6; 8 9]
h =
1 2 3
k =
4
7
m =
5 6
8 9
>> n = [h; k m]
n =
1 2 3
4 5 6
7 8 9
Vectors, as we have seen, are one-dimensional examples of arrays. To create vectors with equally
spaced elements, the colon (:) notation is helpful. The syntax is start value : step size : end value.
The default step size is 1.
40 APPENDIX A. MATLAB OVERVIEW
Function Description Example
ones(m,n) Create an : by n array
lled with ones
ones(2,3) =
1 1 1
1 1 1
zeros(m,n) Same as ones, but lled
with zeros.
zeros(3,2)=
0 0
0 0
0 0
transpose(A) or A. Transpose the array rvec. =
1
2
3
4
size(A) Return the dimensions of
in an array
size(cvec) = 4 1
length(A) Returns the maximal di-
mension of
length(rvec) = 4
: Used to span indices, to TwoDimArray(1:2,2:3)
=
2 3
5 6
Table A.2: Common built-in MATLAB functions useful for dening and manipulating arrays. The examples use
the variables created in Section A.1.5.
Example Code:
>> c = 2:5, d = 9:-1:3
c =
2 3 4 5
d =
9 8 7 6 5 4 3
A useful trick is to use a vector to call indices from another vector. For example, using the above
variable c, we can call the second through the fth values from d in the following way:
Example Code:
>> d(c)
ans =
8 7 6 5
The following are more complex examples of arrays and indices.
Example Code:
>> m = [1.5 -2.4 3.5 0.7; -6.2 3.1 -5.5 4.1; 1.1 2.2 -0.1 0]
m =
1.5 -2.4 3.5 0.7
-6.2 3.1 -5.5 4.1
1.1 2.2 -0.1 0
>> n = m(1:2,2:4), o = m(:,1:2), p = m(2,:)
n =
A.1. BASIC MATLAB INTERFACE 41
-2.4 3.5 0.7
3.1 -5.5 4.1
o =
1.5 -2.4
-6.2 3.1
1.1 2.2
p =
-6.2 3.1 -5.5 4.1
Strings
Strings (or sometimes character strings) are very much like vectors. The dierence is that the
entries are characters instead of numbers. Strings are dened by single quotation marks.
Example Code:
>> str = Signal and System Analysis;
>> disp(str)
Signals and System Analysis
>> str(1:6)
Signal
Strings are useful when we wish to load several les that have been given sequential names (like
data1.dat, data2.dat, etc.). In this case, a for loop may be created that executes commands on the
string data concatenated with the index 1, 2, etc.
Logicals
When MATLAB performs a logical operation (see Section A.2.2), the output is always binary
in nature. That is, the output is an array of 1s and 0s. This output is then dual-purpose:
It contains numbers in indexed positions (like arrays) but it also contains true/false values in
indexed positions. In this sense, logical arrays are very handy because they serve dual purposes
and may be processed very quickly.
There is a key dierence between arrays and logicals regarding indexing. When using an array
to call the index, the value of the elements of the array is important. When using logicals, only the
position of the true elements is important.
Example Code:
>> a = 2:1:5, b = a>3
a =
2 3 4 5
b =
0 0 1 1
>> a(b)
ans =
4 5
>> a([3:4])
ans =
4 5
>> notlogical = [0 0 1 1];
>> a(notlogical)
42 APPENDIX A. MATLAB OVERVIEW
??? Subscript indices must either be real positive integers
or logicals.
The last line is an error because MATLAB thinks we are looking to create an array with the
rst two elements being the 0
element
of a. When MATLAB looks for the 0
=1
t
1.2
/
for times between 0 and 0.8 seconds at intervals of 0.2 seconds, we would execute:
46 APPENDIX A. MATLAB OVERVIEW
Function Description Example
find(a) Returns indices of nonzero
elements
find(a) = 1 3 4 6
find(a>b) Returns indices for which
logical expression is true
find(a>2) = 4 6
max(a,[],d) Returns the maximum el-
ements along the direction
specied
max(a) = 4
min(a,[],d) Returns the minimum ele-
ments along the direction
specied
min(a) = 0
mean(a,d) The average of the elements mean(a) = 1.6667
sum(a,d) The sum of the elements sum(a) = 10
Table A.5: Commonly used data analysis functions. All relevant examples operate on the vector = (1, 0, 2, 3, 0, 4).
The optional arguments [],d can be used to specify the dimension on which the function is to act. In all cases d =
1 operates on columns and returns a row, and d = 2 is the opposite.
Example Code:
t = 0 : 0.2 : 0.8;
x = zeros(size(t));
for k = 1 : 3
x = x + sqrt(k)*t.sqrt(1.2*k);
end
>> x
x =
0 0.3701 1.0130 1.8695 2.9182
In the above example, we initialized the variable x to be all zeros before we executed the for loop.
This is good programming practice because in larger or nested loops, it is faster for the system to
assign values to already existing elements, rather than resize the variable on every iteration.
Nested for loops involve executing entire sub-loops on every iteration of outer loops. In the
example below, m starts at 1, and n runs from 1 to 4 before m advances to 2; Then the process
repeats.
Example Code:
y = zeros(3,4);
for m = 1 : 3
for n = 1 : 4
y(m,n) = m + n;
end
end
>> y
y =
2 3 4 5
3 4 5 6
A.3. FLOW CONTROL 47
4 5 6 7
It is often important to remember to place the semicolon after each line inside of the loops. If
omitted, MATLAB will display that line every time it is iterated. This can signicantly slow the
execution time of a script.
A.3.2 while Statement
The while statement is similar to the for statement except that the loop terminates when a logical
condition is satised. To nd the largest power of 2 that is less than 5,000, we might use
Example Code:
n = 1;
while n*2 < 5000
n = n*2;
end
>> n
n =
4096
Care should be taken when using while loops because there is a possibility that poorly stated
logical conditions may never be satised; this results in an endless loop.
Important: Should you nd yourself in an innite loop, press Control-c in the Command Window
to terminate the current process.
Another common use of while statements is to perform tasks while a certain variable counts
down towards zero. Here it is appropriate to introduce a concept called machine zero. MATLAB
systems have a least counting element, it is the smallest quantity that the system can dierentiate
between numbers. On most modern installations, it is around 10
16
. So if a while loop is set to
run until the counter reaches zero, it will actually run until the counter reaches 10
16
.
This may be a problem if the counter only asymptotically approaches zero. It may take many
iterations to reach the machine zero. In this case, it is useful to dene a number that is close
enough to zero for the loop to terminate. This value, called the stopping point, represents a
trade-o between absolute accuracy and execution speed.
A.3.3 if Statement
The if statement allows us to selectively execute statements based on the outcome of a logical
expression. Further, they can be nested within other loops as well as other if statements.
Example Code:
for k = 1 : 4
if k == 1
x(k) = 3*k;
else
if k == 2 | k == 4
x(k) = k/2;
else
x(k) = 2*k;
48 APPENDIX A. MATLAB OVERVIEW
end
end
end
>> x
x =
3 1 6 2
In addition, if statements are often used to issue warnings or check for data errors before performing
intense calculations.
Example Code:
c = t; n = 2;
if c == f
c = false
y = NaN;
end
d = 0.1 : 0.1 : 0.4;
if c == t
if n == 2
y = 100*d(n);
elseif n == 1
y = 10*d(n);
else
y = 0;
end
end
Which of course yields c = t and y = 20.
When used with if statements, the break command is very useful. If a loop is to be executed
a variable number of times, if statements can be used to check the status of certain criteria, and
then the break command can be issued to halt the loop.
A.4 Plotting
Plottingin two dimensions or threeis an extremely useful tool in the analysis and presentation
of data. Even if they are never destined to be published, plots often give a big picture idea of a
data set that is more valuable than numerical or statistical analysis alone.
As such, MATLAB has a wealth of graphical display functions from the urbane to the imagi-
native. The most basic is the plot(x,y) command. This places a connected plot of the data pairs
r(/), j(/) for all / in the current gure window. The following three lines of code generate the plot
in Figure A.2.
Example Code:
x = linspace(0, 2*pi);
y = sin(x);
plot(x,y);
A.4. PLOTTING 49
Figure A.2: Simple plot generated from three lines of code.
50 APPENDIX A. MATLAB OVERVIEW
Of course, the plot in Fig. A.2 is presentable and the ease with which it was generated is nice.
But it is lacking somewhat in presentation (what are we looking at?) and functionality (why are
we looking at it?). As such, MATLAB provides many more commands to create detailed graphs
and dress them up nicely.
In particular, the plot command itself has many optional arguments. Issuing help plot details
all of the dierent line and marker styles available.
Command Description
figure(a) Makes a the active gure window
hold on Places subsequent plot commands on same axes instead
of replacing them
hold off Releases hold on command
title(text) Places text as a title above the plot
xlabel(text) Labels x-axis of plot with text
ylabel(text) Labels y-axis of plot with vertically rotated text.
text(x,y,text) Places text on the plot at point (r, j)
legend(First,Second) Places a legend that labels two plots on the same axes
axis([x1 x2 y1 y2]) Scales the x- and y-axes to t between r
1
, r
2
, j
1
, and
j
2
subplot(m,n,id) Splits the gure window into an : by n array of plots
with plot number id as the active plot
a
Table A.6: Common plot editing commands
a
In a subplot array, the plots are numbered starting at 1 in the upper left and count across the rst line, then
across the second line, etc.
We now expand on the three-line example above to incorporate some of the commands detailed
in Table A.6. The resulting graph is shown in Figure A.3.
Example Code:
x = linspace(0, 2*pi);
y1 = sin(x);
y2 = cos(x);
ax = [0 2*pi -1.5 1.5];
figure;
subplot(2,1,1)
plot(x,y1,o)
axis(ax)
title(Basic Sinusoids)
ylabel(y-axis)
legend(Sin(x))
subplot(2,1,2)
plot(x,y2,+-)
axis(ax)
xlabel(x-axis)
ylabel(y-axis)
legend(Cos(x))
A.4. PLOTTING 51
Figure A.3: Embellished plots using tools from Table A.6
52 APPENDIX A. MATLAB OVERVIEW
A.5 Signals and Systems Applications
1
In this section, we present several function m-les that have been created specically for signal and
system analysis. On the laboratory computers, these m-les are located in
w:\matlab\toolbox\ee351L
These functions encompass
Step and ramp signal functions
Discrete- and continuous-time Fourier series functions
Continuous-time Fourier transform function
All of the functions contain help statements at the beginning. These statements indicate the
functions purpose, dene input and output variables, and in a few cases provide useful modication
suggestions and requirements.
A.5.1 Step and Ramp Functions
We use step and ramp functions often in signal and system analysis. Therefore, we have created
the MATLAB functions us and ur to compute them. The syntax looks like
u = us(t)
r = ur(t)
The step function us returns n = 0 for t < 0 and n = 1 for t 0. Likewise, ur returns : = 0 for
t < 0 and : = t for t 0.
A.5.2 Continuous-Time Fourier Series Functions
We have created four functions for use in performing Fourier analyses of continuous-time signals.
The rst function computes Fourier series coecients from sample values of a continuous-time
signal. The second function computes samples of the truncated Fourier series approximation to a
signal over a specied time interval. The last two functions compute the Fourier transform and the
inverse Fourier transform, respectively.
Fourier Series Coecients
The function
[Xn, f, ang, No, Fo] = ctfsc(t,x)
computes the Fourier series expansion coecients Xn corresponding to the portion of the signal x
within the expansion interval t(1) - dt/2 to t(ns) + dt/2. This interval has length ns*dt where
ns = size(t,2) is the number of signal samples and dt is the time interval between samples.
There are ns Fourier series coecients computed and the frequency interval between these is
Fo = 1/(ns*dt). Series coecients are computed for both positive and negative frequencies and
the coecient A
0
corresponding to ) = 0 is stored in Xn(No). The values of both No and Fo are
function outputs along with Xn.
The Fourier series expansion interval can begin anywhere between -10*(ns*dt) to 10*(ns*dt).
These limits can be changed, if required, as indicated in the help statements in the m-le.
1
Section A.5 is taken directly from the rst edition of this laboratory manual. Its author is unknown.
A.5. SIGNALS AND SYSTEMS APPLICATIONS 53
Truncated Fourier Series
The second Fourier series function is
[xfs, Xnn] = ctfs(t,Xn,no,fo,N)
This function rst selects the 2N+1 Fourier series coecients, Xnn, centered on A
0
. Then the
function computes samples, xfs, of the truncated Fourier series approximation of r over the time
interval specied by the input variable t. The time interval does not need to be the same as the
expansion interval used to compute the Fourier series coecients.
The input variables Xn, no, and fo are the output variables obtained from the function ctfsc.
This function also plots the Fourier series. The original function can also be plotted on the same
graph by using the hold on command after ctfs followed by the plot command.
Fourier Transform
MATLAB contains a built-in function for the Fourier transform called fft. Using this function
requires knowledge of discrete-time concepts which students in this laboratory are not expected
to know. We have therefore written a function which attempts to create the best approximation
possible to a continuous-time Fourier transform.
The function
[f, X, N, no] = ctft(t,x,dfm)
computes the Fourier transform of the portion of the signal x contained in the interval t(1) - dt/2
to t(ns) + dt/2. This interval has length ns*dt where ns = size(x,2) is the number of signal
samples and dt is the time interval between samples. The signal portion used must begin at
t(1)$\leq 0$ and end at \verbt(ns)= 0. If the signal is longer than the time interval ns*dt,
then the computed transform will have some distortion since it is the transform of the truncated
signal.
There are N Fourier transform samples computed, where N is the larger of
ceil( 1/(dfm*dt) ) or 2*ns. The variable dfm is the maximum spacing that we will allow be-
tween computed transform samples. Note that care must be exercised in selecting dfm and dt since
N can become very large if they are chosen to be quite small. Transform samples are computed for
both positive and negative frequencies with a spacing of df = 1/(N*dt). The transform value at
) = 0 is stored in X(no). The frequencies at the transform sample points are stored in the output
vector f.
Now we can plot the magnitude and phase of the Fourier transform using MATLABs plot
capabilities. We can use the subplot command to plot the amplitude and angle of the transform
on the same page:
Example Code:
subplot(2,1,1)
plot(f,abs(X))
subplot(2,1,2)
plot(f,angle(X))
Due to complications arising from the fact that we are actually using discrete-time signals in
our computations, the phase of the Fourier transform may sometimes be dierent from what is
expected. If this happens, rst try using the unwrap command before plotting the phase. If the
problem still exists, the problem may be that an insucient portion of the signal is begin included
in the samples. Try extending the length of the samples in include a longer portion of the signal.
54 APPENDIX A. MATLAB OVERVIEW
Inverse Fourier Transform
MATLAB contains a built-in function for the inverse Fourier transform called ifft. Using this func-
tion requires knowledge of discrete-time concepts which students in this laboratory are not expected
to know. We have therefore written a function which attempts to create the best approximation
possible to a continuous-time inverse Fourier transform.
The function
[t, x, n] = ctift(f,X,dtm)
computes the inverse, x, of the Fourier transform X. The input vector f species the frequency
interval and sample spacing for the input Fourier transform vector X. These input vectors are
outputs of the function ctft. The number of transform samples is ns = size(X,2), and the
number of inverse transform samples computed, N, is the larger of ceil( 1/(dtm*df) ) or ns.
The variable df is the spacing between transform samples, and the input variable dtm species the
maximum spacing that we allow between computed inverse transform samples. As for the Fourier
transform, we must exercise care in selecting the variables df and dtm so that N does not become
excessively large.
If the magnitude of the transform is an even function of frequency and the phase of the transform
is an odd function of frequency, then the inverse transform should be real. There will probably
be some round-o error present, so in this case you should probably take the real portion of the
inverse transform before plotting. The inverse transform can then be plotted using the standard
MATLAB plot command:
Example Code:
x = real(x);
plot(t,x)
A.5.3 Straight-Line Approximate Bode Plot Functions
Straight-line approximations to Bode amplitude response and Bode phase response plots are conve-
nient in continuous-time system analyses. We have created the two functions sysdat and slbode
to compute the parameters for the straight-line approximations and the straight-line approximation
data, respectively. The location of the system zeros is not restricted. The functions are capable of
nding the parameters and straight-line date for causal, stable systems (poles only in the LHP) and
non-causal, stable systems (poles in both the LHP and RHP). Also, results for marginally stable
systems can be obtained. These results are valid for input signals that do not contain poles located
at single-order system poles on the imaginary axis.
Transfer Function Parameter Computation
The function
[rn, rd, imas, rhps, c, bf, ft, dr] = sysdat(n,d)
computes the transfer function, or frequency response, parameters for a system having the transfer
function
H(:) =
n(1):
+ +n(c): +n(c + 1)
d(1):
+ +d(a): +d(a + 1)
or frequency response
H(,.) =
n(1)(,.)
+ +n(c),. +n(c + 1)
d(1)(,.)
+ +d(a),. +d(a + 1)
BIBLIOGRAPHY 55
The numerator and the denominator coecients are stored int he input vectors n and d, respectively.
Function outputs are described in Table A.7.
Output Variable Description
rn Roots of the numerator (system zeros)
rd Roots of the denominator (system poles)
imas Two-element row vector containing the number of zeros and the
number of poles on the imaginary axis
rhps Two-element row vector containing the number of zeros and the
number of poles in the RHP
c Constant multiplicative factor c = n(i),d(,), where i and , are
the largest integers for which n(i) and d(,) are not equal to zero
bf Row vector containing the break frequency for each factor where,
for linear factors bf 0, bf= 0, and bf 0 indicate LHP, imagi-
nary axis, and RHP poles or zeros, respectively
ft Row vector of factor types where +1 and +2 correspond to nu-
merator linear and quadratic factors, and 1 and 2 correspond
to denominator linear and quadratic factors
dr Row vector of factor damping ratios
Table A.7: Output argument descriptions for the custom function sysdat.
A damping ratio only applies to a quadratic factor and is a number greater than zero but less
than one. We set dr(i) equal to 10 for factor i as an indicator that factor i is a linear factor.
Quadratic factors that correspond to LHP, imaginary axis, and RHP poles are indicated with
positive, zero, and negative damping ratios, respectively.
Note: If a factor is of order , then the data for it will appear as data for rst order factors at
the same break frequency. The data for each of these rst-order factors is the same and the resulting
straight-line approximation for the