User Tools

Site Tools


fft_matlab

Matlab Fast Fourier Transform code

A simple fft Matlab code. Can be obtained here.


Description

This is a simple Matlab code to calculate Fourier transform of a single channel signal using fft. The code is a Matlab function and can be downloaded to any folder and run from there.
To call this function use

[f,A,Ps,Ph]=Power_Spec_Scaled_simple(D,Fs)

Input parameters are

D a vector containing the signal
Fs a sampling frequency value [Hz]

Output parameters are

f resulted frequencies vector
A resulted one-sided amplitudes vector
Ps resulted one-sided power density vector [P/df]
Ph resulted one-sided phase angles vector [rad]

Important notes

The fft works correctly only with data of 2^n elements. Therefore, if this function will detect the total length of the provided signal D and truncate it, if necessary, to the 2^n number of elements, rest of the elements will be discarded. This function returns its products including the DC components at /f/=0.

Code

function [f,A,Ps,Ph]=Power_Spec_Scaled_simple(D,Fs)
%
% Calculates amplitude and scaled power spectra, A and P/df, of a given
% signal D sampled at Fs. No averaging is perfromed here.
% The fft will be perfromed only on the first 2^n elements of the signal,
% the rest of the elements will be discarded.
% The output arguments are the frequency vector f, the A and
% P/df (A and Ps) vectors, and the Ph vector containing corresponding phase
% values. 
% Example of the output structure (8 elements):
% Element #    1  2   3   4   5   6   7   8 
% Frequency    0 1df 2df 3df 4df 3df 2df 1df
% Returned    |_____________|
% Note that 4df frequency element power carries no important information.

y=D(:); % Make sure the signal is a column vector
% Testing and adjusting signal length to be 2^n
n=floor(nextpow2(length(y)));
if n>length(y); n=n-1; end;

DNFFT=2^n; y=D(1:DNFFT);
df=Fs/DNFFT; % frequency resolution
Y = fft(y,DNFFT)/DNFFT;
f = df.*[0:DNFFT/2-1];
A=2*(abs(Y(1:DNFFT/2)));
Ps=A.^2./df;
% correct phases:
% Y=fft(y);
Ph=angle(Y(1:DNFFT/2));
fft_matlab.txt · Last modified: by 127.0.0.1

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki