Kennedy asked . 2021-04-02

How to plot frequency spectrum of a signal in matlab?

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');

 

spectrum of a signal spectrum of a signal spectrum of a signal

matlab , signal , signal processing

Expert Answer

Neeta Dsouza answered . 2025-02-28 04:40:12

Your code is close to generating a frequency spectrum, but it needs adjustments to ensure it correctly computes and visualizes the frequency content of your signal. Here's a step-by-step guide to correct and refine your code:


Key Issues and Fixes:

  1. Frequency Axis Definition:

    • The frequency axis calculation (f = fs/2*linspace(-1,1,fs);) is incorrect. The number of points in fftSignal determines the resolution of the frequency axis.
  2. FFT Normalization:

    • The magnitude of the FFT should be scaled by the number of samples to ensure proper amplitude representation.
  3. Positive Frequencies:

    • For a real-valued signal, the FFT output is symmetric. Only positive frequencies need to be plotted.
  4. Clear Titles and Labels:

    • Use descriptive titles and labels to distinguish between the time-domain and frequency-domain plots.

Updated Code:

 

close all;
clear;

% Define parameters
fs = 8000;          % Sampling frequency in Hz
f = 400;            % Signal frequency in Hz
t = 0:1/fs:1-1/fs;  % Time vector (1 second duration)

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

% Plot time-domain signal
figure;
plot(t, signal);
title('Time-Domain Signal');
xlabel('Time (s)');
ylabel('Amplitude');

% Compute FFT
N = length(signal);             % Number of samples
fftSignal = fft(signal);        % Perform FFT
fftSignal = fftSignal / N;      % Normalize FFT output

% Compute frequency axis
f = (0:N-1)*(fs/N);             % Frequency vector (0 to fs)
halfRange = 1:floor(N/2);       % Consider only the positive frequencies

% Plot frequency spectrum
figure;
plot(f(halfRange), abs(fftSignal(halfRange))); % Magnitude spectrum
title('Frequency Spectrum of Signal');
xlabel('Frequency (Hz)');
ylabel('Magnitude');

% Add noise
noise = 2*randn(size(signal));  % Generate random noise
noisySignal = signal + noise;   % Add noise to the signal

% Plot time-domain noisy signal
figure;
plot(t, noisySignal);
title('Time-Domain Noisy Signal');
xlabel('Time (s)');
ylabel('Amplitude');

% Compute FFT of noisy signal
fftNoisySignal = fft(noisySignal);
fftNoisySignal = fftNoisySignal / N;

% Plot frequency spectrum of noisy signal
figure;
plot(f(halfRange), abs(fftNoisySignal(halfRange))); % Magnitude spectrum
title('Frequency Spectrum of Noisy Signal');
xlabel('Frequency (Hz)');
ylabel('Magnitude');

Improvements:

  1. FFT Normalization:

    • Dividing by NN ensures that the FFT's magnitude correctly represents the signal's amplitude.
  2. Frequency Axis:

    • Properly aligned with the number of FFT bins and includes only positive frequencies.
  3. Focus on Positive Frequencies:

    • Real signals result in symmetric FFT outputs. Plotting only the positive frequencies avoids redundancy.
  4. Readable Outputs:

    • Separate plots for the time-domain signal, frequency spectrum, and noisy signal make interpretation easier.

Output:

  1. Time-Domain Signal:

    • A clean sine wave at 400 Hz.
  2. Frequency Spectrum:

    • A single peak at 400 Hz for the clean signal.
    • For the noisy signal, the spectrum includes both the signal's peak and noise spread across frequencies.

This version adheres to the proper definition of the frequency spectrum and should satisfy your lecturer’s expectations. Let me know if you need further clarifications!


Not satisfied with the answer ?? ASK NOW

Frequently Asked Questions

MATLAB offers tools for real-time AI applications, including Simulink for modeling and simulation. It can be used for developing algorithms and control systems for autonomous vehicles, robots, and other real-time AI systems.

MATLAB Online™ provides access to MATLAB® from your web browser. With MATLAB Online, your files are stored on MATLAB Drive™ and are available wherever you go. MATLAB Drive Connector synchronizes your files between your computers and MATLAB Online, providing offline access and eliminating the need to manually upload or download files. You can also run your files from the convenience of your smartphone or tablet by connecting to MathWorks® Cloud through the MATLAB Mobile™ app.

Yes, MATLAB provides tools and frameworks for deep learning, including the Deep Learning Toolbox. You can use MATLAB for tasks like building and training neural networks, image classification, and natural language processing.

MATLAB and Python are both popular choices for AI development. MATLAB is known for its ease of use in mathematical computations and its extensive toolbox for AI and machine learning. Python, on the other hand, has a vast ecosystem of libraries like TensorFlow and PyTorch. The choice depends on your preferences and project requirements.

You can find support, discussion forums, and a community of MATLAB users on the MATLAB website, Matlansolutions forums, and other AI-related online communities. Remember that MATLAB's capabilities in AI and machine learning continue to evolve, so staying updated with the latest features and resources is essential for effective AI development using MATLAB.

Without any hesitation the answer to this question is NO. The service we offer is 100% legal, legitimate and won't make you a cheater. Read and discover exactly what an essay writing service is and how when used correctly, is a valuable teaching aid and no more akin to cheating than a tutor's 'model essay' or the many published essay guides available from your local book shop. You should use the work as a reference and should not hand over the exact copy of it.

Matlabsolutions.com provides guaranteed satisfaction with a commitment to complete the work within time. Combined with our meticulous work ethics and extensive domain experience, We are the ideal partner for all your homework/assignment needs. We pledge to provide 24*7 support to dissolve all your academic doubts. We are composed of 300+ esteemed Matlab and other experts who have been empanelled after extensive research and quality check.

Matlabsolutions.com provides undivided attention to each Matlab assignment order with a methodical approach to solution. Our network span is not restricted to US, UK and Australia rather extends to countries like Singapore, Canada and UAE. Our Matlab assignment help services include Image Processing Assignments, Electrical Engineering Assignments, Matlab homework help, Matlab Research Paper help, Matlab Simulink help. Get your work done at the best price in industry.