Example 1
Suppose we want to average daily stock prices taken over last
year to yield a running weekly average (average over five
trading sessions). The filter we want is a length-5 averager
(as shown in the
unit-sample response), and the input's
duration is 253 (365 calendar days minus weekend days and
holidays). The output duration will be
253+5-1=257
253
5
1
257
, and this determines the transform length we need to
use. Because we want to use the FFT, we are restricted to
power-of-two transform lengths. We need to choose any FFT
length that exceeds the required DFT length. As it turns out,
256 is a power of two (
28=256
2
8
256
), and this length just undershoots our required length. To
use frequency domain techniques, we must use length-512 fast
Fourier transforms.
Figure 1 shows the input and the
filtered output. The MATLAB programs that compute the filtered
output in the time and frequency domains are
Time Domain
h = [1 1 1 1 1]/5;
y = filter(h,1,[djia zeros(1,4)]);
Frequency Domain
h = [1 1 1 1 1]/5;
DJIA = fft(djia, 512);
H = fft(h, 512);
Y = H.*X;
y = ifft(Y);
note:
The filter program has the "feature"
that the length of its output equals the length of its
input. To force it to produce a signal having the proper
length, the program zero-pads the input
appropriately.
MATLAB's
fft function automatically
zero-pads its input if the specified transform length (its
second argument) exceeds the signal's length. The frequency
domain result will have a small imaginary component —
largest value is
2.2×10-11
2.2-11
— because of the inherent finite precision nature of
computer arithmetic. Because of the unfortunate misfit between
signal lengths and favored FFT lengths, the number of
arithmetic operations in the time-domain implementation is far
less than those required by the frequency domain version: 514
versus 62,271. If the input signal had been one sample
shorter, the frequency-domain computations would have been
more than a factor of two less (28,696), but far more than in
the time-domain implementation.
An interesting signal processing aspect of this example is
demonstrated at the beginning and end of the output. The
ramping up and down that occurs can be traced to assuming the
input is zero before it begins and after it ends. The filter
"sees" these initial and final values as the difference
equation passes over the input. These artifacts can be handled
in two ways: we can just ignore the edge effects or the data
from previous and succeeding years' last and first week,
respectively, can be placed at the ends.