3,167 views (last 30 days)

Show older comments

Hi. I want to plot frequency spectrum of a signal. I got this coding based on the sources that I found from the internet but my lecturer said this is not frequency spectrum. Can somebody help me on this?

close all;

%Define number of samples to take

fs = 8000;

f = 400; %Hz

%Define signal

t = 0:1/fs:1-1/fs;

signal = sin(2*pi*f*t);

%Plot to illustrate that it is a sine wave

plot(t, signal);

title('Time-Domain signal');

%Take fourier transform

fftSignal = fft(signal);

%apply fftshift to put it in the form we are used to (see documentation)

fftSignal = fftshift(fftSignal);

%Next, calculate the frequency axis, which is defined by the sampling rate

f = fs/2*linspace(-1,1,fs);

%Since the signal is complex, we need to plot the magnitude to get it to

%look right, so we use abs (absolute value)

figure;

plot(f, abs(fftSignal));

title('magnitude FFT of sine');

xlabel('Frequency (Hz)');

ylabel('magnitude');

%noise

noise = 2*randn(size(signal));

figure, plot(t,noise), title('Time-Domain Noise');

fftNoise = fft(noise);

fftNoise = fftshift(fftNoise);

figure, plot(f,abs(fftNoise)), title('Magnitude FFT of noise');

xlabel('Frequency (Hz)');

ylabel('magnitude');

%noisy signal

noisySignal = signal + noise;

figure, plot(t,noisySignal), title('Time-Domain Noisy Signal');

fftNoisySignal = fft(noisySignal);

fftNoisySignal = fftshift(fftNoisySignal);

figure, plot(f,abs(fftNoisySignal)), title('Magnitude FFT of noisy signal');

xlabel('Frequency (Hz)');

ylabel('magnitude');

Salaheddin Hosseinzadeh
on 26 Oct 2015

Hi there!

I don't know why your instructor didn't like it! Maybe it's missing a division and he is picky on that!

fftNoisySignal = fft(NoisySignal)./numel(NoisySignal);

Maybe that is the case, basically the magnitude of the fft has an issue, I guess! You need to apply this division on every fft command you use.

Hope this helps.

Good luck!

Jonas
on 1 May 2021 at 14:26

Image Analyst
on 26 Oct 2015

Edited: Image Analyst
on 26 Oct 2015

Salaheddin Hosseinzadeh
on 27 Oct 2015

As Image Analyst said there are several different methods. Some of which have different names. Power spectrum, Power spectrum density and ... each of which have slightly different method of calculation. Yet, the simple fft is the heart of them, which is performed correctly in your code.

You already accepted my answer, tnx, but if your problem was not and you're looking for something specific search and if no success let me know :)

Good Luck!

AMADI OKO
on 22 Mar 2019

Image Analyst
on 22 Mar 2019

Viktor Bolgov
on 1 Dec 2019

Sandro Yemi Okutuga
on 14 Aug 2020

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!