% Example - How to create a frequency spectrum in MatLab:
% Barukyah Shaparenko and John M. Cimbala

clear all
close all

% Import time t and voltage data f(t) from Excel
% NOTE: You must put the Excel data file in the same folder as the MatLab m-file
%
% The format of the data in the Excel file must match what we read here:
%       Cell B3 = N (number of data points)
%       Cell B4 = f_s (sampling frequency)
%       Cell A7 = first time data point (the time column is column A)
%       Cell B7 = first f(t) data point (the f(t) column is column B)
%
xls_filename = 'Excel_data_file_for_Matlab_FFT';
sheet_number = 1;
N = xlsread(xls_filename,sheet_number,'B3');
f_s = xlsread(xls_filename,sheet_number,'B4');
time_column = 'A'; % Column letter
frequency_column = 'B'; 
first_row = 7; % Row number
last_row = first_row + N;
first_row = num2str(first_row);
last_row = num2str(last_row);
data_range1 = [time_column first_row ':' time_column last_row];
t = xlsread(xls_filename,sheet_number,data_range1); % time data
data_range2 = [frequency_column first_row ':' frequency_column last_row];
f = xlsread(xls_filename,sheet_number,data_range2); % signal data

%Calculated values:

T = N/f_s; % Total sample time (s)
del_t = 1/f_s; 
del_f = 1/T;
f_fold = f_s/2; % Folding frequency = max frequency of FFT
N_freq = N/2; % Number of discrete frequencies

% FFT of the time signal

for k = 0:N/2
    frequency(k+1) = k*del_f;
end

%NFFT = 2^nextpow2(N); % Use power of 2 for FFT (NOT necessary in Matlab, but faster)
%F = fft(f,NFFT);   % Compute FFT for case with integer multiple of 2 data points
F = fft(f,N);       % Compute FFT for general case: N not necessarily a multiple of 2

for k =0:N/2
    Magnitude(k+1) = abs(F(k+1))/(N/2);
end
Magnitude(1) = Magnitude(1)/2; % Divide first term by a factor of 2

% Plot the frequency spectrum

figure(1)
hold on;
% plot(frequency,Magnitude,'-bo','MarkerFaceColor','r','MarkerEdgeColor','r','LineWidth',2)
plot(frequency,Magnitude,'LineWidth',2)
% title('FFT Frequency Spectrum','FontWeight','Bold','FontSize',16)
xlabel('frequency, f (Hz)','FontWeight','Bold')
ylabel('|F|','FontWeight','Bold')
xmin = 0;
xmax = f_fold;
xlim([xmin xmax])
grid
hold off;
