Signal_Final_TikeaTE/frequencySpectrum.m

59 lines
1.4 KiB
Matlab

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