From c7035c6f6af02513dd31f2b1e93b75005e0992d8 Mon Sep 17 00:00:00 2001 From: Tikea TE Date: Wed, 16 Apr 2025 14:34:13 +0200 Subject: [PATCH] add the frequencySpectrum.m to plot the power spectrum --- frequencySpectrum.m | 58 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 frequencySpectrum.m diff --git a/frequencySpectrum.m b/frequencySpectrum.m new file mode 100644 index 0000000..e45a6ad --- /dev/null +++ b/frequencySpectrum.m @@ -0,0 +1,58 @@ +function [f,power] = frequencySpectrum(signal,freq_sampling,plt) +%{ +function [f,power] = frequencySpectrum(signal,freq_sampling,plt) +ex: [f,power] = frequencySpectrum(x, 40, 1) + +Task: to generate the power spectrm of a signal + +Inputs: + -signal: the signal that we want to get FFT + -freq_sampling: how many samples we want per second + +Outputs: + -f: vector of frequency + -power: power spectrum of the input signal + +Author: Tikea TE +Date: 11/04/2025 +%} + +n = length(signal); % this is our number of samples + +% generate the frequency vector +f = (0:n-1)*(freq_sampling/n); % fs/n is the frequency resolution, it tells how many hz are between each bin + +% generate the power vector +y = fft(signal,n); % compute DFT of the signal with the same length +power = abs(y).^2/n; % compute the power(spectrum) of the DFT of the signal + +% find the max value of the power and its index +[val,ind] = max(power); + +% plotting the figure +if (plt) + figure; + subplot(1,3,1) % time plot + t=0:1/freq_sampling:(n-1)/freq_sampling; % time range + plot(t, signal) + xticks(0:0.1*freq_sampling:n); + xticklabels(0:0.1:n/freq_sampling); + xlabel('Time (s)'); + ylabel('Amplitude (a.u.)'); + + subplot(1,3,2) % linear frequency plot + plot(f,power, 'b*'); hold on; + plot(f,power, 'r'); + xlabel('Frequency (Hz)') + ylabel('Power (a.u.)') + + subplot(1,3,3) % log frequency plot + plot(f,10*log10(power/power(ind))); + xlabel('Frequency (Hz)') + ylabel('Power (dB)') +end + + + + +