Hi Max,
To plot the spectral analysis of your signal in MATLAB, you can use the Fast Fourier Transform (FFT) to convert the time-domain signal into its frequency-domain representation.
First, you will need to define your sampling frequency "Fs" and compute the time vector "t". Generate the signal "A" using a sine function with frequency "F_A" (440 Hz for note A) and play it using the sound function. To analyze the frequency content, apply the "fft" function to the signal "A", which yields a two-sided spectrum "P2". From "P2", derive the single-sided spectrum "P1" by taking half of "P2" and doubling the amplitude of all components except the first and last. Create a frequency vector "f" that corresponds to the frequency bins of the "FFT" output.
Finally, plot the single-sided amplitude spectrum using "plot", with frequency on the x-axis and amplitude on the y-axis.
The below code snippet illustrates the above approach:
function plotSpectralAnalysis(app)
% Sampling frequency and time vector
Fs = 8000;
Ts = 1 / Fs;
t = 0:Ts:1;
% Signal generation
F_A = 440; % Frequency of note A is 440 Hz
A = 2 * sin(2 * pi * F_A * t);
% Play the sound
sound(A, Fs);
% Perform FFT
L = length(A); % Length of signal
Y = fft(A);
P2 = abs(Y / L); % Two-sided spectrum
P1 = P2(1:L/2+1); % Single-sided spectrum
P1(2:end-1) = 2 * P1(2:end-1);
% Frequency vector
f = Fs * (0:(L/2)) / L;
% Plot the spectral analysis
figure; % Open a new figure window
plot(f, P1);
title('Single-Sided Amplitude Spectrum of A(t)');
xlabel('Frequency (f) [Hz]');
ylabel('|P1(f)|');
end
For more details, please refer to the following MathWorks documentations:
- Spectral analysis - https://www.mathworks.com/help/dsp/ug/spectral-analysis.html#:~:text=Spectral%20analysis%20is%20done,and%20averaging%20the%20transform.
- fft - https://www.mathworks.com/help/matlab/ref/fft.html
Hope this helps!