Wednesday, October 18, 2017

[Matlab] PSD (Power Spectral Density)

https://www.mathworks.com/help/signal/ug/power-spectral-density-estimates-using-fft.html

Example
-------------------------------------------
function handles = PSDPlotFnc(hObject,eventdata,handles)

% Load the data
result = handles.result;
% Retrieve x data
xi = get(handles.xVariables,'Value');
t = result{xi,1};
% Retrieve y data
yn = get(handles.VariablesList,'String');
yi = get(handles.VariablesList,'Value');
yn = yn{yi,1}; y = result{yi,1};

% Sampling time Ts and sampling frequency Fs
Ts = t(2) - t(1);
Fs = 1/Ts;

% Data length
N = length(y);

% FFT
ydft = fft(y);
ydft = ydft(1:N/2+1);
psdy = ( 1+(Fs*N) ) * abs(ydft).^2;
psdy(2:end-1) = 2*psdy(2:end-1);
freq = 0:Fs/length(y):Fs/2;

% Plot
pline = plot(handles.axes1,freq,10*log10(psdy),'DisplayName',yn);
hl = legend(handles.axes1,'-DynamicLegend');
set(hl,'interpreter','none');
xlabel(handles.axes1,'Frequency [Hz]');
ylabel(handles.axes1,'Power/Frequency [dB/Hz]');
grid(handles.axes1,'on');


No comments:

Post a Comment