Sie sind auf Seite 1von 23

2/12/2020 EDN - Real spectrum analysis with Octave and MATLAB - Steve Hageman

Advertisement


< https://www.edn.com/>

DESIGN < HTTPS://WWW.EDN.COM/CATEGORY/DESIGN/>

DESIGN HOW-TO < HTTPS://WWW.EDN.COM/CATEGORY/DESIGN/DESIGN-HOW-


TO/>

Real spectrum analysis with Octave and MATLAB

AUGUST 6, 2015 <  COMMENTS 0 <


HTTPS://WWW.EDN.COM/REAL-SPECTRUM- HTTPS://WWW.EDN.COM/REAL-
ANALYSIS-WITH-OCTAVE-AND-MATLAB/> SPECTRUM-ANALYSIS-WITH-
BY STEVE HAGEMAN < OCTAVE-AND-
HTTPS://WWW.EDN.COM/AUTHOR/STEVE- MATLAB/#RESPOND>
HAGEMAN/>

A set of functions are presented for Octave/MATLAB that allow easy, consistent, and properly scaled
DFT/FFT analysis of signals and noise. The techniques and functions presented are easily translated to
other scripting or compiled programming languages.

I use Fourier Transforms on time domain data all the time now, whether it's measuring OPAMP noise or
looking for spurious signals with my digital oscilloscope acting as the digitizer. Being able to get a
calibrated spectrum display is very useful when verifying and troubleshooting nearly any design.

Most modern oscilloscopes now have a DFT/FFT1 < http://www.edn.com/design/test-and-


This website uses cookies. By continuing to browse it, you are agreeing
measurement/4440068/9/real-spectrum-analysis-with-octave-and-matlab#references> to our
display mode
use ofand
built in cookies More
that's fine, but info < https://aspencore.com/privacy-policy/>
you are stuck using the built-in definitions and DFT implementation and I have
yet to see one that will handle noise measurements properly. Also, you may just have data from some
other source that you would like to quickly analyze. Close and accept

https://www.edn.com/real-spectrum-analysis-with-octave-and-matlab/ 1/23
2/12/2020 EDN - Real spectrum analysis with Octave and MATLAB - Steve Hageman
While there are many examples on the Web of using DFT functions that show how to make a spectrum
for signal analysis or power spectral density for noise analysis, many are not fully accurate, hard to use,
or even worse, not compatible with each other. All of this confusion leads to a lot of wasted time. These
problems lead me to create a set of consistent analysis functions for Octave/MATLAB2 <
http://www.edn.com/design/test-and-measurement/4440068/9/real-spectrum-analysis-with-octave-
and-matlab#references> that I use all the time for calibrated DFT signal and noise analysis in a unified,
easy to remember, and consistent form.

With Octave, data from any source may be analyzed and generally Octave is quicker than traditional
programming languages when a solution needs to be developed fast.

Every DFT analysis starts with an input signal

When testing DFTs a method of quickly generating test signals is needed. There are literally millions of
function snippets on the Web for generating signals but they all use a different approach and that makes
them hard to remember and reuse. I have found that I need to generate deterministic signals in two
forms:

1. Generate a deterministic signal with a known number of sine wave cycles.


That way I can test windowing functions with whole and fractional cycles to
easily determine amplitude accuracy, etc.
2. Generate a deterministic signal based on a sampling approach. This form
is useful when I want to make a 10,000 point vector of a 10 kHz sine wave
sample at a sampling rate of 100 kHz. This is useful when thinking in terms
of an actual digitized signal.

Then for white noise signals:

To generate Gaussian white noise with a given Power Spectral Density (PSD) in real units that we analog
folks use all the time, like: Vrms/√Hz.

Note that in all these examples, and for the rest of this discussion, the units for the input signal are
normally assumed to be in Vrms. If the data is in different units then it should be scaled appropriately
back into Vrms units before continuing the signal processing.

Starting with the generation of sine wave signals. For scenario #1 above the function: “tonecycles.m” is
used as shown in Figure 1 . 

This website uses cookies. By continuing to browse it, you are agreeing to our
% Make an input signal (Sine Wave Tone) based on number of cycles
use of= cookies
cycles 3.95; % More
Numberinfo
of<cycles
https://aspencore.com/privacy-policy/>
to make
points = 1000; % Number of points to generate
amp = 1; % Amplitude Vrms Close and accept

https://www.edn.com/real-spectrum-analysis-with-octave-and-matlab/ 2/23
2/12/2020 EDN - Real spectrum analysis with Octave and MATLAB - Steve Hageman
time_data = tonecycles(amp, cycles, points);

Figure 1 To make a sine wave signal based on the number of cycles generated, the
function “tonecycles.m” is used. The resulting output plot is shown. Note that
fractional or whole cycles can be generated as shown in this example.

If a sinewave based on sampling is needed, use the tonesampling() function as shown in Figure 2 .

% Make an input signal (Sine Wave Tone) based on sampling


fs = 100000; % Sampling Rate Hz
fsig = 500; % Tone Frequency Hz
points = 1000; % Points
amp = 1; % Amplitude Vrms

time_data = tonesampling(amp, fsig, fs, points);

This website uses cookies. By continuing to browse it, you are agreeing to our
use of cookies More info < https://aspencore.com/privacy-policy/>

Close and accept

https://www.edn.com/real-spectrum-analysis-with-octave-and-matlab/ 3/23
2/12/2020 EDN - Real spectrum analysis with Octave and MATLAB - Steve Hageman

Figure 2 To make a sine wave signal based on a sampling approach, the function
“tonesampling.m” is used. The resulting output plot is shown (bottom).
See the example file: “generate_sinewaves_example.m” on the last page of the article <
http://www.edn.com/design/test-and-measurement/4440068/9/real-spectrum-analysis-with-octave-
and-matlab> for a complete Octave example of Figures 1 and 2 with plots.

To make white noise of a specified power spectral density, the function: “noisepsd.m” is used as shown in
Figure 3 . A complete working Octave example of the noisepsd() function is provided in the file:
“generate_noise_example.m”.

% Noise PSD Setup (Random Noise)


fs = 10000; % Sampling Rate Hz
points = 10000; % Points
amp = 1.0; % Amplitude Vrms / rt-Hz

% Calculate the noise


noise_data = noisepsd(amp, fs, points);

This website uses cookies. By continuing to browse it, you are agreeing to our
use of cookies More info < https://aspencore.com/privacy-policy/>

Close and accept

https://www.edn.com/real-spectrum-analysis-with-octave-and-matlab/ 4/23
2/12/2020 EDN - Real spectrum analysis with Octave and MATLAB - Steve Hageman

Figure 3 Making a specific power spectral density for simulation is not as easy as
one might think. The power spectral density must not change as the length of the DFT
and the sampling rate changes, so the noisepsd() function takes this into account and
no matter what the length or sampling rate of the DFT, the result will always have the
proper power spectral density after applying a properly scaled for noise DFT.

Basic DFT function and scaling

Doing an accurately scaled DFT with Octave or any scientific language should be easy, however this is
almost never the case. All the different DFT methods scale the DFT results differently or not at all, leading
to inaccurate results and confusion. The first task is to make a wrapper for the Octave default DFT
function that scales the result properly.

Usually the basic DFT in Octave is based on the FFTW implementation.3 <
http://www.edn.com/design/test-and-measurement/4440068/9/real-spectrum-analysis-with-octave-
and-matlab#references> This is a very fast optimized DFT that can handle any length of input signals,
but is optimized for power of two input data lengths where it uses the classic FFT algorithm. FFTW will
also handle prime number input lengths very efficiently. If real time speed is of utmost importance to you,
then you should definitely understand the tradeoffs in speed versus input data length. However for most
desktop type of analysis with real world data sets any data length will give reasonable performance on a
modern PC. It has been my experience that you will have a much more difficulty plotting large data sets
This website uses cookies. By continuing to browse it, you are agreeing to our
on a PC than analyzing them in the first place.
use of cookies More info < https://aspencore.com/privacy-policy/>
Most DFT algorithms also return a mirrored spectrum (a real and imaginary frequency spectrum),
Closeonly
however for normal spectrum analysis, as would be seen on a spectrum analyzer display, andtheaccept
real
frequency portion of the DFT is needed. This means that the DFT result needs to be chopped in two for

https://www.edn.com/real-spectrum-analysis-with-octave-and-matlab/ 5/23
2/12/2020 EDN - Real spectrum analysis with Octave and MATLAB - Steve Hageman
the returned spectrum, and this chopping in two removes energy that must be accounted for by scaling
also.

While there are many ways of implementing DFTs and FFTs and all these require different scaling
methodologies, all the PC-based DFT implementations that I have seen use the simple 1/N and Sqrt(2)
scaling. One of the properties of an unscaled DFT is that the amplitude of a deterministic signal scales as
the number of DFT points changes (or DFT bin width changes). In a real spectrum display however, the
RMS signal amplitude must stay the same no matter the span of the analysis. The output magnitude of a
DFT is the RMS voltage of the signal in every DFT bin. Referring to the code snippet below, the 1/N and
the 2/Sqrt(2) adjusts the scaling such that a 1 Vrms input signal will be 1 Vrms in the magnitude DFT
output.

Also of note is the fact that the first and last points of the DFT's real frequency span are different and
must be scaled differently. These points correspond to DC and Fs/2 (or the Nyquist Frequency). By
definition DC and Fs/2 have no phase component in the complex DFT result, hence the need to scale
them differently. However even this scaling is imperfect in practice. If a window is used then the energy in
the DC portion will smear into adjacent bins and those bins won't be scaled properly, etc. The best way to
deal with DC is to remove it from the time series data first, and the easiest method to do that is to simply
find the average value of all the time series input data points and then subtract this average value from
the time data before performing the DFT.4 < http://www.edn.com/design/test-and-
measurement/4440068/9/real-spectrum-analysis-with-octave-and-matlab#references> Many real
measuring instruments don't use these first and last DFT points for display purposes because of the
difficulty of keeping them scaled properly.

% DFT the input, get complex vector result,


% x is the input time series vector.
y = fft(x);

% Remove the mirror image of the spectrum,


% L is the calculated 1/2 length of the DFT.
y = y(1:L);

% Scale entire DFT by 1/N or length(x).


y = y / length(x);

% Scale every point except first and last properly,


% The 2 is because we use only 1/2 the calculated spectrum,
% The sqrt(2) converts properly to RMS values.
y(2:end-1) = (2 / sqrt(2)) * y(2:end-1);

% Convert complex DFT to real #'s and return mag^2 result.


mag2 = abs(y).^2;
This website uses cookies. By continuing to browse it, you are agreeing to our
use of cookies
The magnitude Moreresult
squared info is
< https://aspencore.com/privacy-policy/>
a natural return result. Many researchers still like to think in terms of V 2

for signals or V /Hz for noise because this is proportional to power. Magnitude squared values are also
2

Close
the natural place to average multiple DFTs because any noise will be averaged properly and
at this accept
step.

https://www.edn.com/real-spectrum-analysis-with-octave-and-matlab/ 6/23
2/12/2020 EDN - Real spectrum analysis with Octave and MATLAB - Steve Hageman
To reduce the magnitude squared result to the more normal electrical engineering units of Vrms for
signals or V/√Hz for noise just take the square root of the magnitude squared values.

When no windowing is used on the data, the code snippet shown above will give a correctly scaled V2
RMS result for a deterministic signal like a sine wave tone at a DFT bin center.
Zero padding the DFT

Zero padding a DFT involves adding zeros to the windowed input time series to make the apparent total
time series longer. Zero padding will increase the apparent frequency resolution of a DFT. Generally this
is used to see fine detail in window functions and on a practical level many instruments implement zero
padding to improve the appearance of the resulting display (see References 5-8 <
http://www.edn.com/design/test-and-measurement/4440068/9/real-spectrum-analysis-with-octave-
and-matlab#references> ). Another reason to zero pad is to increase the DFT length of a real data
series up to a power of two length so that the DFT algorithm can use the much faster FFT
implementation.

The addition of zeros adds more frequency bins and that spreads the energy of any signals over more
bins. This affects the basic scaling of the DFT. To get back to the proper scaling, the zero padded DFT
result can be multiplied by the following correction factor,

ZeroPadded_Scale_Factor = (N + Nz) / N

where N is the original waveform data set size and Nz is the number of zero padded points that were
added.

Putting this all together, the Octave Library function provided here: “dftmag2.m” has two forms. The first is
to do a DFT of the input time series (corresponding to the code outline shown previously), returning the
single sided magnitude squared DFT result (vector ma2) and optionally the frequency span (vector
Fspan) of the DFT for easy X/Y plotting as shown below:

% Example A – Perform a DFT on the vector time_series.


% Fs is the sampling frequency in Hz
% Returns a vector of Magnitude^2 values and optionally,
% Fspan a vector of the frequency bins.
[ma2, Fspan] = dftmag2(time_series, Fs);

% Example B – Perform a DFT with Nz added zeros.


% Returns a vector of Magnitude^2 values and optionally,
% Fspan a vector of the frequency bins.
[ma2, Fspan] = dftmag2(time_series, Fs, Nz);
This website uses cookies. By continuing to browse it, you are agreeing to our
use of cookies More info < https://aspencore.com/privacy-policy/>
Example A above executes a DFT on the “time_series” vector of input data points. Example B additionally
adds Nz zeros to the “time_series” data before performing the DFT. The parameter “Fs” is the sampling
Close and accept
frequency which is used along with the calculated length of the “time_series” to return the vector “Fspan”
which contains the center frequency of each DFT bin, this allows for easy X/Y plotting of the result. The
https://www.edn.com/real-spectrum-analysis-with-octave-and-matlab/ 7/23
2/12/2020 EDN - Real spectrum analysis with Octave and MATLAB - Steve Hageman
magnitude result of the DFT is the vector ma2, which is the properly scaled, single sided result in
magnitude squared format. The return units are then, RMS V2 (RMS volts squared) for deterministic
signals. Noise signals require another scaling step as will be discussed later.

Complete example code showing a working sample of both forms of the dftmag2() function usage is
provided in the example named: “dftmag2_example.m”.
Windowing input data

A DFT works by assuming that the time series data being transformed is a continuous function for infinity
time both before and after the data series to be analyzed. This can easily be simulated by having only
whole cycles in the time data and this is the same as saying that the input frequency lies directly in the
center of one of the DFT bins. In real life data this is rarely the case, and the result of imperfect real data
is to cause the DFT to have all sorts of sidebands that can be very high in amplitude and may cause
nearby smaller signals to disappear from view. The solution is to apply a windowing function to the time
data that tapers the input data toward zero at the beginning and end of the data series.

There are many types of windows that have been developed from simple to quite complex functions and
there are just as many theories and myths about what window to use in what application.

One of the best papers written on windows8 < http://www.edn.com/design/test-and-


measurement/4440068/9/real-spectrum-analysis-with-octave-and-matlab#references> presents all
the common forms in a logical and consistent fashion of increasing amplitude accuracy and sideband
suppression. That paper also presents several new very high performance flat top windows. The Octave
windowing function presented here is based on this reference.

There are no perfect window functions, they all involve tradeoffs. Lowering the side lobes always
increases the width of the main lobe. The same problem exists for amplitude accuracy. Non-perfect data
will have an amplitude error that is normally referred to as scolloping error. This amplitude error happens
when a deterministic input signal is not directly in the center of a bin. Scolloping error looks like passband
ripple in the resulting display. As the signal is tuned from one bin center to another, the amplitude will
appear to ripple up and down. With no window (also called the rectangular window) the scolloping error is
nearly 1.57 to 1 (or 3.9 dB) for a deterministic sine wave signal. The best normal window, like the Kaiser 5
from Reference 8 < http://www.edn.com/design/test-and-measurement/4440068/9/real-spectrum-
analysis-with-octave-and-matlab#references> can reduce the scolloping ripple to 0.64 dB. Flat top
windows are used to get the ripple down to almost nothing at the expense of a much broader main
window and much lower sideband suppression.

The Octave function provided on the last page of this article < http://www.edn.com/design/test-and-
measurement/4440068/9/real-spectrum-analysis-with-octave-and-matlab> named: “dftwindow.m” will
generate windows coefficients to be applied to the input data before doing the actual DFT. This function is
easily used as follows,
This website uses cookies. By continuing to browse it, you are agreeing to our
use of cookies More info < https://aspencore.com/privacy-policy/>
% Generate a vector of window coefficients for the named window type
% and given length: points. Close and accept
wc = dftwindow('hamming', points) ;

https://www.edn.com/real-spectrum-analysis-with-octave-and-matlab/ 8/23
2/12/2020 EDN - Real spectrum analysis with Octave and MATLAB - Steve Hageman
% The Window Coefficients may then be applied to the time series data
windowed_series = time_series .* wc;

Given a length of window to produce coefficients for (normally the same length as the time series data)
the generated set of windows coefficients (in vector form) are easily multiplied directly to the time series
input data vector as shown above.

Reference 8 < http://www.edn.com/design/test-and-measurement/4440068/9/real-spectrum-


analysis-with-octave-and-matlab#references> contains 34 different types of windows and the function
“dftwindow.m” referenced above can produce each of these by the same name as shown in Table 1
below. Additionally an adjustable Kaiser window is implemented that takes an extra parameter, alpha:

wc = dftwindow('kaiser', points, alpha);

Normally in a Kaiser window as implemented here, the alpha ranges between 2 to 5, but it can be any
positive floating point number.9 < http://www.edn.com/design/test-and-measurement/4440068/9/real-
spectrum-analysis-with-octave-and-matlab#references>

If you have a favorite window not mentioned here, then it is easy to extend the 'dftwindow.m' function or
write your own Octave “.m” function to implement it.

Table 1 The windows' names as implemented in the supplied Octave function:


“dftwindow.m”. These names correspond to the ones used in Reference 8 <
http://www.edn.com/design/test-and-measurement/4440068/9/real-spectrum-analysis-with-octave-
and-matlab#references> .For purists, 'hanning' can also be called 'hann' and
'rectangular' can be called 'none' (The names shadow each other). The adjustable
Kaiser window also requires an alpha adjustment value.

Window scaling for signals


This website uses cookies. By continuing to browse it, you are agreeing to our
use of cookies More info < https://aspencore.com/privacy-policy/>
While applying a window function to our time domain data can improve our DFT results, the window
function can have a negative effect on how the DFT signal finally ends up scaled (Figure 4 ). In most of
Close and accept
the classical references on windows, the window function itself is usually normalized to be equal to 1 at
the center of the window, this will then cause a loss of amplitude accuracy after the DFT is performed. A
https://www.edn.com/real-spectrum-analysis-with-octave-and-matlab/ 9/23
2/12/2020 EDN - Real spectrum analysis with Octave and MATLAB - Steve Hageman
simple way to analyze any set of windows coefficients to determine an appropriate scaling factor is by the
use of the Octave function: “dftscale.m” provided on the last page of this article <
http://www.edn.com/design/test-and-measurement/4440068/9/real-spectrum-analysis-with-octave-
and-matlab#references> ,

% Derive the scale factor for the given window coefficients


scale_factor = dftscale(wc, 'signal');

This website uses cookies. By continuing to browse it, you are agreeing to our
use of cookies More info < https://aspencore.com/privacy-policy/>

Close and accept

https://www.edn.com/real-spectrum-analysis-with-octave-and-matlab/ 10/23
2/12/2020 EDN - Real spectrum analysis with Octave and MATLAB - Steve Hageman

Figure 4 At top, a Hamming window is shown applied to a series of time data. The
bottom plot shows the results of a DFT on this time series. Note that the application of
the window has changed the vertical scale of the DFT output. The result should have
been 1 Vrms, but as can be seen is closer to 0.54 Vrms in the improperly scaled
result.
For deterministic signals such as sine wave signals, the scale factor of a window may be determined as
simply,

% Find Window Scale for Signal – snippet from 'dftscale.m'


s1 = sum(wc) / N;
sf = (1 / s1)^2;

Where, 'wc' is the vector containing the windows coefficients and 'N' is the length of 'wc'. Then 'sf' is the
resultant scale factor.

This scale factor is then applied to the DFT magnitude squared result as shown,

% Find the proper window scale factor for deterministic signals


% and apply to the DFT Magnitude Squared result
[ma2, fspan] = dftmag2(windowed_time_data, fs);
This
sf =website uses
dftscale(wc, cookies. By continuing to browse it, you are agreeing to our
'signal');
scaled_dft = ma2 * sf;
use of cookies More info < https://aspencore.com/privacy-policy/>

Windows scaling for noise Close and accept

https://www.edn.com/real-spectrum-analysis-with-octave-and-matlab/ 11/23
2/12/2020 EDN - Real spectrum analysis with Octave and MATLAB - Steve Hageman
The analysis of DFT data for deterministic signals and noise is handled differently, and hence the scaling
needs to be different. The power spectral density (PSD) of noise is normally presented as either V2 /Hz or
V/√Hz. The noise is expressed as a density and it is always expressed with a bandwidth, whereas a
deterministic signal has no bandwidth associated with it. This has implications in a DFT as the bandwidth
of a bin is determined by the sampling frequency of the signal and the number of DFT points,

Resulting DFT Bin Width = Sampling Frequency / DFT Points

If the number of DFT points (or time series data length) is equal to the sampling rate, then the resulting
DFT bin width will be 1 Hz and whatever power spectral density we measure in each DFT bin will be
normalized to 1 Hz. If we change the number of points in our DFT however, we will see a different value
in each bin unless we apply a scale factor that takes into account the actual bin width in Hz. For example,
if the DFT points is 10 times less than the sampling rate, then the DFT bin width will be 10 Hz and the
Vrms noise in each DFT bin will be √10 times more than the 1 Hz normalized case.

The same applies to any windowing function we use. Recall that any window has the effect of broadening
the signal into adjacent bins. The effect on noise is then to smear some of the noise in one bin to adjacent
bins. A window function acts like an analog filter and it has a noise bandwidth associated with it.

The normalized equivalent noise bandwidth (NENEB) of any set of windows coefficients may be
calculated as

% Determine Normalized Noise Bandwidth of a Window


s1 = sum(wc) / N;
s2 = sum(wc.^2);
nenbw = (s2/(s1^2)) / N;

where N is the number of points or length of the window coefficients vector (wc).

To measure the power spectral density of noise properly, then we need a scale factor that takes into
account the noise bandwidth of the applied window and the DFT bin width. The “dftscale.m” function
supplied on the last page of this article < http://www.edn.com/design/test-and-
measurement/4440068/9/real-spectrum-analysis-with-octave-and-matlab> has a 'noise' option to
calculate this for us,

% Find window scale factor for noise signals


% and apply to the DFT Magnitude Squared result
[ma2, fspan] = dftmag2(windowed_time_data, fs);
[sf, nenbw] = dftscale(wc, 'noise', fs);
scaled_dft = ma2 * sf;
This website uses cookies. By continuing to browse it, you are agreeing to our
use of cookies More info < https://aspencore.com/privacy-policy/>
By using the parameter 'noise' and supplying the sampling frequency (fs) in the dftscale.m function, the
proper scale factor for noise will be calculated for any window coefficients and the actual
CloseDFT bin accept
and width.

https://www.edn.com/real-spectrum-analysis-with-octave-and-matlab/ 12/23
2/12/2020 EDN - Real spectrum analysis with Octave and MATLAB - Steve Hageman
The optional returned parameter “nenbw” is the noise bandwidth as classically calculated above and is
useful in determining the noise bandwidth for any set of windows coefficients.

Notice that the scale factor is calculated with dftscale.m function and is applied to the magnitude squared
result at the same place in the process if the signal type is a deterministic signal or noise, even though
the scale factor for 'signal' is different than for 'noise'.

The signal or noise may be calculated and scaled properly from the same DFT result (or magnitude
squared data). It is not possible to properly display signal amplitudes and noise amplitudes correctly on
the same display, however. This is demonstrated by looking at how a typical spectrum analyzer works. A
spectrum analyzer normally always displays the signal amplitudes accurately. If one wishes to measure
noise, a special noise marker is activated that corrects for the window (or noise bandwidth) and DFT bin
width and will properly display the noise on the selected portion of the display. Specialized noise
analyzers work differently, they typically display the noise directly and when a signal is detected in the
data they switch to a “spurious mode” in the display so that the signal may be scaled properly. This can
result in a somewhat disjointed looking display, but it is useful and about the only way that signals and
noise can be displayed with amplitude accuracy together.

Proper averaging DFT results

Averaging is used to reduce the variance of noise in our measurements, and especially when dealing with
noise it is important to average at the right step in the process to preserve the true mean value of the
noise.

The basic operations are shown below:

% Make a blank vector to hold the sum.


vector_sum = zeros(points/2+1, 1);

% Average the noise DFT's given: num_averages


for i = 1:num_averages

% Simulate some noise, but this step might acquire


% actual data in a real world example.
% Apply window 'wc' if desired to the time series
noise_data = noisepsd(amp, fs, points) .* wc;

% Perform a DFT on the raw noise data


% Return are Magnitude Squared Values
This
ma2 website uses cookies.
= dftmag2(noise_data, fs); By continuing to browse it, you are agreeing to our
use of cookies More info < https://aspencore.com/privacy-policy/>
% Accumulate the vector sum
vector_sum = vector_sum + ma2; Close and accept

https://www.edn.com/real-spectrum-analysis-with-octave-and-matlab/ 13/23
2/12/2020 EDN - Real spectrum analysis with Octave and MATLAB - Steve Hageman

endfor

% Calculate the final vector average in MAG^2 Units


ma2_average = vector_sum ./ num_averages;

See the example file: “generate_noise_example.m” on the last page of this article <
http://www.edn.com/design/test-and-measurement/4440068/9/real-spectrum-analysis-with-octave-
and-matlab> for a complete working example of properly averaging and measuring the mean of noise
signals.

Sometimes real world time series data is accumulated in big chunks and the desire is to divide this big
series into smaller chunks for averaging. The built-in Octave function: 'reshape()' can be used to divide a
large vector of data into smaller ones that can be processed and averaged.

In the following example, a large vector of random noise is created, then this large vector is resized into
10 smaller chunks for analysis.

% Make an input signal (Sine Wave Tone)


fs = 100000; % Sampling Rate Hz
points = 100000; % Points
amp = 1; % Amplitude Vrms / rt-Hz

% Calculate a large noise vector


time_data = noisepsd(amp, fs, points);

% Resample the array into 10 chunks using the function: reshape()


chunks = 10;
time_data_chunked = reshape(time_data, points/chunks, chunks);

% Set a window for the chunks


wc = dftwindow('none', points/chunks);

% Setup the average


vector_sum = zeros((points/chunks)/2+1, 1);

% Average the chunks


for i = 1:chunks
This website uses cookies. By continuing to browse it, you are agreeing to our
use of cookies
% Preform More
a DFT on the info < https://aspencore.com/privacy-policy/>
current chunk, return a Magnitude^2 result
ma2 = dftmag2(time_data_chunked(:, i) .* wc, fs);
Close and accept
% Accumulate the vector sum
https://www.edn.com/real-spectrum-analysis-with-octave-and-matlab/ 14/23
2/12/2020 EDN - Real spectrum analysis with Octave and MATLAB - Steve Hageman
vector_sum = vector_sum + ma2;

endfor

% Calculate vector average


ma2_average = vector_sum / chunks;

% Get the scaled magnitude data from the DFT Results


scaled_mag_dft = sqrt(ma2_average);

Two complete examples named: “resample_data_tone.m” and “resample_data_noise.m” are provided in


the example directory listed on the last page of this article < http://www.edn.com/design/test-and-
measurement/4440068/9/real-spectrum-analysis-with-octave-and-matlab> that show how to
accomplish averaging as above.

Converting to other units

So far we have shown how to take a time series and get a result that is properly scaled in Vrms for
signals. Conversion to other units may be done after this step. For instance to convert signal amplitudes
to dBV the following conversion can be done,

% Perform a DFT on some time series


ma2 = dftmag2(time_series, fs);

% Get the magnitude data from the DFT Result


scaled_mag_dft = sqrt(ma2);

% Convert to dBV format (Or another appropriate format here)


dBV_result = 20 * log10(scaled_mag_dft);

Purists will notice that the sqrt() function can be absorbed into the above dBV calculation at the
magnitude squared step thus saving a sqrt() calculation, but for simplicity the solution is shown in a
straight forward manner that will work for any final format of the result.

Review of basic analysis steps

The Octave functions presented here are applied in the same consistent sequence for deterministic
signals and noise. The basic steps are outlined below,
This website uses cookies. By continuing to browse it, you are agreeing to our
use of cookies More info < https://aspencore.com/privacy-policy/>
1) Generate or acquire the time series input data. Functions for signal generation are,
tonecycles()
tonesampling()
Close and accept
noisepsd()
https://www.edn.com/real-spectrum-analysis-with-octave-and-matlab/ 15/23
2/12/2020 EDN - Real spectrum analysis with Octave and MATLAB - Steve Hageman
2) Generate the desired window coefficients and multiply to the time series data,
dftwindow()

3) Perform the DFT, with appropriate zero padding if desired. Return is the DFT in magnitude squared
format,
dftmag2()

4) Average the DFT magnitude squared result bin by bin at this point if needed.

5) Calculate the scale factor for the particular window and DFT length combination. Then multiply the
resulting scale factor to the DFT magnitude squared result. A decision must be made here as to whether
the final result is to be scaled as a signal or noise,
dftscale()

6) Take the square result of the scaled magnitude squared DFT to get the more usual EE units of Vrms or
Vrms/√Hz .

7) The results can be further scaled to: dBV, dBuV, or dBm as required.

Files available for download and usage

The files are available on Sourceforge here < http://dftfunctionswithoctave.sourceforge.net> .

The zip file there contains two folders. The first folder named “DFT” contains all the Octave functions
outlined in this paper. The easiest way to have these functions automatically recognized is to place them
in the directory as shown.

Placing user developed Octave functions in the “…sitem” directory allows Octave to find anything placed
there for use without any further setup steps required as these folders are in the standard search path.
This website uses cookies. By continuing to browse it, you are agreeing to our
use of cookies
Naturally More ainfo
if you are using < https://aspencore.com/privacy-policy/>
different version of Octave or you haven't installed Octave in the default install
path, the exact directory path will be different.
Close and accept

https://www.edn.com/real-spectrum-analysis-with-octave-and-matlab/ 16/23
2/12/2020 EDN - Real spectrum analysis with Octave and MATLAB - Steve Hageman
The second folder in the zip file is named “examples.” This directory contains fully working examples of all
the functions presented in this paper. These will be helpful as a framework for further work and for
understanding how the pieces are all put together in actual use.

Online help

Once the files are installed, online help in Octave is available for any function by typing,

>>help function_name

on the command line.

For instance typing,

>>help dftscale

will display the following help information,

— Function File: SF = dftscale (WC, 'signal')


— Function File: [SF, NENBW] = dftscale (WC, 'noise', FS)

Return SF: Scale Factor for the supplied window coefficients and
analysis type. The Scale Factor is to be applied to the DFT Magnitude^2.

For noise analysis the optional parameter: NENBW The Normalized Noise Equivalent Bandwidth is also
returned.

Input WC: Vector of window coefficients to be analyzed.

Input 'signal': Specifies that the scale factor is to becalculated for a 'signal' analysis.

Input 'noise': Specifies that the scale factor is to be calculated for a 'noise' analysis.

Input FS: When 'noise' type of analysis is specified, the Sample Rate in Hz must also be specified.

References
This website uses cookies. By continuing to browse it, you are agreeing to our
use of cookies
1. Most authors use< the
More info term FFT to mean any sort of Fourier transform, when in fact a
https://aspencore.com/privacy-policy/>
true FFT is a special case of the DFT. In this paper I use the more general term
Discrete Fourier Transform (DFT). If you scale the input data lengthClose and of
to powers accept
two

https://www.edn.com/real-spectrum-analysis-with-octave-and-matlab/ 17/23
2/12/2020 EDN - Real spectrum analysis with Octave and MATLAB - Steve Hageman
or even prime numbers, almost all the generalized Fourier Transforms as
implemented will pick the fastest method for you, automatically.
2. These programs were developed with Version 4.0.0 of Octave, they should also work
for MATLAB without modification, but this has not been strictly tested. For the
remainder of this article I will use the term Octave but imply both Octave and
MATLAB. For more information on Octave, visit this page <
http://www.gnu.org/software/octave/> . MATLAB is a registered trademark of
The MathWorks, Inc. For more information see this page <
http://www.mathworks.com/products/matlab/> .
3. Fastest Fourier Transform in the West (FFTW). More information on FFTW
can be found here < http://www.fftw.org> .
4. The Octave function “detrend.m” may be used for more comprehensive DC
removal algorithms. See this page for more info.
5. “Measuring Frequency Response and Effective Bits using Digital Signal
Processing Techniques,” Hewlett-Packard Journal, February 1992, Page
29.
6. “Vector Signal Analyzers for Difficult Measurements of Time-Varying and
Complex Modulated Signals,” Hewlett-Packard Journal, December 1993,
Page 9.
7. “Detector Selection for Spectrum Analyzer Measurements,” Joe Gorin, RF
Design, February 2003.
8. G. Heinzel, A. Rudiger and R. Schilling, Max-Planck-Institut fur
Gravitationsphysik, February 15, 2002. “Spectrum and spectral density
estimation by the Discrete Fourier transform (DFT), including a
comprehensive list of window functions and some new flat-top windows”
9. The adjustable Kaiser Window as implemented here follows the form
presented on this Wikipedia page < https://en.wikipedia.org/?title=kaiser-window>
(As Retrieved June 25, 2015)

Author information

Steve Hageman is a confirmed “analog-a-holic” since about the fifth grade when he
built his first shortwave receiver. After acquiring his first his first Apple computer in
1982, he has continued using software to control analog hardware and building useful
measurement systems. Steve has had the pleasure of designing such diverse products
as: Modular Data Acquisition Systems, Switching Power Supplies, RFIC Test Systems,
This website uses cookies.
Software By continuing
Defined Radios to browse
and most recently, Precisionit,High
you are agreeing
Frequency Lock In to our
use of cookies
Amplifiers for biological
More sample
info <investigation and imaging.
https://aspencore.com/privacy-policy/>

Steve may be reached via his website, AnalogHome < http://www.analoghome.com> .


Close and accept
Also see :
https://www.edn.com/real-spectrum-analysis-with-octave-and-matlab/ 18/23
2/12/2020 EDN - Real spectrum analysis with Octave and MATLAB - Steve Hageman

– GNU Octave hits a high note < http://www.edn.com/electronics-blogs/the-practicing-


instrumentation-engineer/4428091/gnu-octave-hits-a-high-note>
– A Look at Octave (vs. SciLab) < http://www.edn.com/electronics-
blogs/benchtalk/4428650/a-look-at-octave--vs--scilab->
– An engineer’s software toolbox update < http://www.edn.com/electronics-
blogs/analog-ic-startup/4421151/an-engineer-s-software-toolbox-update>
– 6 GHz spectrum analysis in your hand! < http://www.edn.com/electronics-blogs/the-
emc-blog/4434756/6-ghz-spectrum-analysis-in-your-hand->

0 C O M M E N T S O N “ R E A L S P E C T R U M A N A LY S I S W I T H O C TAV E A N D
M AT L A B ”

L EAVE A REPLY

You must Register or Login to post a comment.

P R E V I O U S P O S T < H T T P S : / / W W W. E D N . C O M / H I G H - C U R R E N T- C A B L I N G - S Y S T E M -
F R O M - A M P H E N O L - M E E T S - E N E R G Y- S TO R A G E - N E E D S / >
N E X T P O S T < H T T P S : / / W W W. E D N . C O M / N E W- C L E A R S L I D E - V I D E O - M A I L - L E T S -
S E L L E R S - E A S I LY- S E N D - P E R S O N A L I Z E D - V I D E O S - T H AT- B O O S T- C U S TO M E R -
E N G A G E M E N T- 6 0 / >

This website uses cookies. By continuing to browse it, you are agreeing to our
use of cookies More info < https://aspencore.com/privacy-policy/>
Advertisement
Close and accept

https://www.edn.com/real-spectrum-analysis-with-octave-and-matlab/ 19/23
2/12/2020 EDN - Real spectrum analysis with Octave and MATLAB - Steve Hageman

PARTNER CONTENT

Innovating for a
better future

By Industrial Technology Research


Institute, 10.12.2019

Strong industrial
security with the IEC
62443 standard
By Infineon Technologies, 28.10.2019

Taiwan Startup
Challenges Google in
Gesture Recognition
By KaiKuTek , 07.10.2019

Recent Posts

Right-first-time PCB layout for spacecraft avionics < https://www.edn.com/right-first-time-pcb-


layout-for-spacecraft-avionics/> / Medical supply handles high peak loads <
https://www.edn.com/medical-supply-handles-high-peak-loads/> / Forced air cooling vs. wind
chill: Same principle, different reality < https://www.edn.com/forced-air-cooling-vs-wind-chill-
same-principle-different-reality/> / Teardown: Failed mobile power pack <
https://www.edn.com/teardown-failed-mobile-power-pack/> / Ensure EMC compliance in
automotive LED design < https://www.edn.com/ensure-emc-compliance-in-automotive-led-
design/>

Recent Comments
This website uses cookies. By continuing to browse it, you are agreeing to our
yes on Teardown: Failed mobile power pack < https://www.edn.com/teardown-failed-mobile-
use of cookies More info < https://aspencore.com/privacy-policy/>
power-pack/#comment-27126>

George Gulalo on Motor, drive, and control consultant in Los Angeles < Close and accept
https://www.edn.com/motor-drive-and-control-consultant-in-los-angeles/#comment-27125>
https://www.edn.com/real-spectrum-analysis-with-octave-and-matlab/ 20/23
2/12/2020 EDN - Real spectrum analysis with Octave and MATLAB - Steve Hageman

studleylee on Teardown: Failed mobile power pack < https://www.edn.com/teardown-failed-


mobile-power-pack/#comment-27124>

studleylee on Teardown: Failed mobile power pack < https://www.edn.com/teardown-failed-


mobile-power-pack/#comment-27123>

Peter Rathfelder on Teardown: Failed mobile power pack < https://www.edn.com/teardown-failed-


mobile-power-pack/#comment-27122>

Archives

Select Month

Categories

Select Category

This website uses cookies. By continuing to browse it, you are agreeing to our
use of cookies More info < https://aspencore.com/privacy-policy/>

Close and accept

https://www.edn.com/real-spectrum-analysis-with-octave-and-matlab/ 21/23
2/12/2020 EDN - Real spectrum analysis with Octave and MATLAB - Steve Hageman

PODCAST

SOC / 26:40

China's $28B Big Fund


● The Cockiest Startup
● Sony's AImbitions
China collected a huge pot of
money to build a bigger
semiconductor industry. Now
comes the hard part. ● Nuvia
aims to take on Intel in the
data center server market —
but how? ● Sony is taking on
Facebook and Google for AI
supremacy. What are its
prospects?

VIEW ALL EPISODES

LISTEN

This website uses cookies. By continuing to browse it, you are agreeing to our
use of cookies More info < https://aspencore.com/privacy-policy/>

Close and accept

https://www.edn.com/real-spectrum-analysis-with-octave-and-matlab/ 22/23
2/12/2020 EDN - Real spectrum analysis with Octave and MATLAB - Steve Hageman

Advertisement

Search … SEARCH

This website uses cookies. By continuing to browse it, you are agreeing to our
use of cookies More info < https://aspencore.com/privacy-policy/>

Close and accept

https://www.edn.com/real-spectrum-analysis-with-octave-and-matlab/ 23/23

Das könnte Ihnen auch gefallen