A Fourier Series Matlab code - matlab

I have created this code in order to calculate and sketch the Fourier Coefficients A0 ,An ,and Bn without using Fourier Series command but,unfortunately the plots results did not look like a Fourier Series. if someone please guide me to solve this problem.
thank you
I identified all the terms that i am going to use in this project
T=1; %Time Period
wo=2*pi/T;
a0=0;% coefficient
A0=0;% coefficient
a1=0;% coefficient
A1=0;% coefficient
a2=0;% coefficient
A2=0;% coefficient
a3=0;% coefficient
A3=0;% coefficient
a4=0;% coefficient
A4=0;% coefficient
a5=0;% coefficient
A5=0;% coefficient
a6=0;% coefficient
A6=0;% coefficient
a7=0;% coefficient
B7=0;% coefficient
b1=0;% coefficient
B1=0;% coefficient
b2=0;% coefficient
B2=0;% coefficient
b3=0;% coefficient
B3=0;% coefficient
b4=0;% coefficient
B4=0;% coefficient
b5=0;% coefficient
B5=0;% coefficient
b6=0;% coefficient
B6=0;% coefficient
b7=0;% coefficient
B7=0;% coefficient
in this step. i want to calculate the values of my function and store them in a Matrix.
x=0:0.1:T; % x is the time axis
k=1:T/0.1+1;
funcation=x;
F(k)=funcation;
for x=0:0.1:T;
k=1:T/0.1+1;
a0=F(k)+a0;
end
A0=0.1*a0/T;
for x=0:0.1:T;
k=1:T/0.1+1;
b1=F(k).*sin(1.*wo.*x)+b1;
b2=F(k).*sin(2.*wo.*x)+b2;
b3=F(k).*sin(3.*wo.*x)+b3;
b4=F(k).*sin(4.*wo.*x)+b4;
b5=F(k).*sin(5.*wo.*x)+b5;
b6=F(k).*sin(6.*wo.*x)+b6;
b7=F(k).*sin(7.*wo.*x)+b7;
end
for x=0:0.1:T;
B1=0.1.*2.*b1./T.*sin(1.*wo.*x);
B2=0.1.*2.*b2./T.*sin(2.*wo.*x);
B3=0.1.*2.*b3./T.*sin(3.*wo.*x);
B4=0.1.*2.*b4./T.*sin(4.*wo.*x);
B5=0.1.*2.*b5./T.*sin(5.*wo.*x);
B6=0.1.*2.*b6./T.*sin(6.*wo.*x);
B7=0.1.*2.*b7./T.*sin(7.*wo.*x);
end
bq=B1+B2+B3+B4+B5+B6+B7;
for x=0:0.1:T;
k=1:T/0.1+1;
a1=F(k).*cos(1.*wo.*x)+a1;
a2=F(k).*cos(2.*wo.*x)+a2;
a3=F(k).*cos(3.*wo.*x)+a3;
a4=F(k).*cos(4.*wo.*x)+a4;
a5=F(k).*cos(5.*wo.*x)+a5;
a6=F(k).*cos(6.*wo.*x)+a6;
a7=F(k).*cos(7.*wo.*x)+a7;
end
for x=0:0.1:T;
A1=0.1.*2.*a1./T.*cos(1.*wo.*x);
A2=0.1.*2.*a2./T.*cos(2.*wo.*x);
A3=0.1.*2.*a3./T.*cos(3.*wo.*x);
A4=0.1.*2.*a4./T.*cos(4.*wo.*x);
A5=0.1.*2.*a5./T.*cos(5.*wo.*x);
A6=0.1.*2.*a6./T.*cos(6.*wo.*x);
A7=0.1.*2.*a7./T.*cos(7.*wo.*x);
end
aq=A1+A2+A3+A4+A5+A6+A7;
FQ=bq+aq+A0;
plot(F(k))
figure
plot(FQ)

The problem is in defining for loops in your script.
You shouldn't insert a semicolon ; at the end of for expression.
Instead of:
for x=0:0.1:T;
you should omit ; and write it like:
for x=0:0.1:T
then the plots work fine and both plots will be identical. As your function here is y=x, it would be a 45 degree line.

Related

How can find the Fourier Coefficents of this DFT?

I have a data which contains 16 elements:
x=[8.57837e-08, 2.07482e-06, 4.43796e-06, 7.66462e-06, 1.10232e-05, 1.35811e-05, 1.27958e-05, 5.94217e-06, 2.49168e-08, -6.58389e-06, -1.30551e-05, -1.345e-05, -1.07471e-05, -7.38637e-06, -4.42876e-06, -1.88811e-06 ];
A = length(x)
I do DTFT-DFT like dirac signals:
n=0:A;
syms w
X_w=0;
for i=1:length(x)
X_w=X_w+x(i)*exp(-j*w*n(i));
end
figure;fplot(angle(X_w),[0 2*pi]),title('DTFT phase graph')
figure;fplot(abs(X_w),[0 2*pi]),title('DTFT amplitude graph')
hold on
%DFT
N=50;
k=0:N-1;
DFT_X=[];
for k=0:N-1
Xk=0;
for i=1:length(x)
Xk=Xk+x(i).*exp(-j*(2*pi/N).*k.*n(i));
end
DFT_X=[DFT_X Xk];
end
w=2*pi/N*(0:N-1);
stem(w,abs(DFT_X))`
The problem is I want to write this signal with cosinus and sinus components. But I don't really know how can I do.
Thank you all,
Emre.
Direct computation of the Fourier coefficients might be a better option than trying to relate the DFT to the DFS. Looking at the continuous time formulas:
all you'd need to do is sum the input signal x multiplied (element wise) by a cosine over it's domain for the real coefficient and sum the input signal x multiplied (element wise) by a sine over its domain for the imaginary coefficients.
Secondly, you could potentially use conjugate symmetry and these formulas to calculate the relationship between your Xk and the desired An and Bn coefficients.
Xk = (An-j*Bn)/2
and
Xk* = (An+j*Bn)/2)

Matlab Fourier Deconvolution

I tried to deconvolute a measured spectrum (Sm) with the pure spectrum (S0) to get the apodization and instrument line shape. Here are the files: Sm and S0
However, I found that the result of my ifft of Sm and S0 are similar. It should give me Gaussian line shape, but I got triangular. What is my mistake and how to solve it?
Thank you in advance.
close all
clear all
clc
sm=load('n2o_gaussian.txt'); %loading spectrum with gaussian ILS
s0=load('n2o_noapodization.txt'); %loading pure spectrum
v=s0(:,1); %wavenumber of pure spectrum
s0_y=s0(:,2); %y component of S0
L=length(v); %length of data
n=2^(nextpow2(L)*2); %number of the next power of two data for FFT
vm=sm(:,1); %wavenumber of measured spectrum
v0=2217.241; %v0 is peak location
vv0=v*ones(1,length(v0))-ones(length(v),1)*v0; %vv0 is wavenumber difference
sm_interpl=interp1( vm, sm, v, 'spline',0); %fit the measured spectrum to match the grid
%pure spectrum
sm_interpl_y=sm_interpl(:,2); %y component of Sm
%y-deconvolution of Sm with S0
s0_y_ift=ifft(s0_y,n,'symmetric'); %inverse FFT of pure spectrum, the symmetric option
enforces imaginary part should be zero in DFT
s0_y_ift=fftshift(s0_y_ift);
sm_interpl_ift=ifft(sm_interpl_y,n,'symmetric'); %inverse FFT of measured spectrum, without
symmetric, half of amplitude will lost
sm_interpl_ift=fftshift(sm_interpl_ift);
apo_y=(sm_interpl_ift)./(s0_y_ift); %get the apodization function from division of sm
and s0
ILS_y=fft(apo_y,n); %get the ILS
ILS_y2=fftshift(ILS_y);
%normalize the area of ILS
area=trapz(f,ILS_y2);
ILS_y2_normalized=ILS_y2./area;
%showing spectra and spline result
figure (1)
plot (sm(:,1),sm(:,2),'o');
hold on;
plot (sm_interpl(:,1),sm_interpl(:,2));
hold on
plot (s0(:,1),s0(:,2));
legend('Measured spectrum','fitted spectrum','pure spectrum')
hold on;
%showing interferogram results
figure (2)
plot(real(sm_interpl_ift))
hold on
plot(real(s0_y_ift))
legend('interferogram of Sm','interferogram of S0')
hold on
%showing apodization function
figure (3)
plot(real(apo_y))
legend('apodization function')
hold on
%showing retrieved ILS
figure (4);
plot(f,real(ILS_y2_normalized));
xlim([-0.0001 0.0001]);
legend('ILS');
hold on;

calculate discrete S transform for given discrete time series

let us consider following Page :
http://djj.ee.ntu.edu.tw/S_Transform.pdf
paragraph 2.3 The Discrete S Transform
let say that we have sampled version of signal x, and given sampling frequency fs,i have calculated discrete Fourier transform using following code
function y=DFT(x);
N=length(x);
D=zeros(N,N);
for k=1:N
for n=1: N
D(k,n)=exp((-j*(k-1)*2*pi*(n-1))/N);
end
end
y=D*x'/N;
end
and started to estimate discrete S transform
function [S]=discrete_s_transform(x,fs);
%compute discrete s transform
%fs-sampling frequency
N=length(x); % length of signal
T=1/fs; % sampling period
Y=DFT(X);
how can i continue related to this part ?
clearly loops are not problem to implement,just they go from 1 to N instead of 0 to N-1 because of matlab vectors are 1 based,but what about main code?multiplication to exponential? coudl you please help me to finish S transform ?
Your sum depends only on m so I assume that other parameters as well as function H((m+n)/(NT)) are defined. Via for-loops the simplest one is:
function [S]=discrete_s_transform(x);
N=length(x); % length of signal
S=0;
m=0;
for i=1:N
S=S+H((m+n)/(NT))*exp(a)*exp(b*m/N);
m=m+1;
end
Hope that helps!

compressive sensing and Haar wavelet

I want to use CS to reconstruct an image from fewer samples.
I use Gaussian random matrix as measurement matrix. My problem is with Psi matrix which I want to be Haar wavelet coefficients but I don't know how to define it.
I have used DCT and Fourier basis and it worked well. Here is my code with Fourier basis.
Can anyone tell me how to define Psi matrix as haar wavelet transform?
Thanks in advance.
clc
clear all
close all
[fn,fp]=uigetfile({'*.*'});
tic
A=im2double(rgb2gray(imread([fp,fn])));
figure(1),imshow(A)
xlabel('original')
x=A(:);
n=length(x);
m=1900;
Phi=randn(m,n); %Measurment Matrix
Psi=fft(eye(n)); %sensing Matrix( or can be dct(eye(n)) )
y=Phi*x; %compressed signal
Theta=Phi*Psi;
%Initial Guess: y=Theta*s => s=Theta\y
s2=Theta\y;
%Solution
s1=OMP( Theta, y, 1e-3);
%Reconstruction
x1=Psi*s1;
figure,imshow(reshape(x1,size(A))),xlabel('OMP')
toc
You just need to generate a haar matrix of appropriate dimensions. Consider this MATLAB function:
function [h]=haargen(N)
% Generating Haar Matrix
ih=zeros(N,N);
h(1,1:N)=ones(1,N)/sqrt(N);
for k=1:N-1
p=fix(log(k)/log(2));
q=k-(2^p);
k1=2^p; t1=N/k1;
k2=2^(p+1); t2=N/k2;
for i=1:t2
h(k+1,i+q*t1) = (2^(p/2))/sqrt(N);
h(k+1,i+q*t1+t2) =-(2^(p/2))/sqrt(N);
end
end

How do I obtain Energy spectrum of a signal after FFT in Matlab?

EDIT:
I stumbled on this explanation to obtain the energy spectrum from an IEEE paper(Open Circuit Fault Diagnosis in 3 phase uncontrolled rectifiers, Rahiminejad, Diduch, Stevenson, Chang).
"A recorded sample of the signal containing a number of samples equivalent to 4T is captured and its FFT is determined using an FFT size equal to the record length (where T is the fundamental period).
Assuming the FFT size is matched to 4 periods of a periodic waveform, every 4th FFT bin will coincide with a harmonic frequency, in particular the center of FFT bin 4k+1 will coincide with the kth harmonic frequency.
The energy of the kth harmonic is calculated as the sum of the squared magnitudes of the 5 consecutive FFT values centred at bin 4k+1. The additional FFT values are included in the harmonic energy calculation so as to reduce the sensitivity of the calculated energy to an error in the frequency estimate which oculd result in the kth harmonic peak shifting away from bin 4k+1."
I do not fully understand the passage above. In my limited understanding, the bold line
refers to the sum of the squared magnitudes of the output of function fft(), i.e. the complex fourier series coefficients.
Can someone please show some light into obtaining the energy spectrum ?
#fpe : I am not sure if ESD performs the same as energy spectrum. BTW, thanks alot for your answer:)
I am trying to plot the energy spectrum of a signal to look at the for example Normalised energy contained first three harmonics, energy ratio of fundamental to 2nd harmonics etc....
Here I have managed to get the Hanning window FFT amplitude-Hz and power-Hz. But, I have no idea how to get energy-Hz for each frequency components.
Any help is much appreciated !
function [f,Xall_Wnd]=fftplotExxx(time,X_input)
Fs = 20000; % Sampling frequency
x = X_input;
% Fast Fourier Transform
L = length (X_input); % Length of FFT
nfft = 2^nextpow2(L); % Next power of 2 from length of signal
%wave = wave.*hamming(length(wave));
x_HammingWnd = x.*hamming(L);
% Take fft, padding with zeros so that length(X)
%is equal to nfft
Xall_Wnd = fft(x_HammingWnd, nfft)/L; %hamming window fft
% FFT is symmetric, throw away second half
% Take the magnitude of fft of x
mx_Wnd = 2*abs(Xall_Wnd(1:nfft/2+1));
% To get Power of x(t) by sqr of magnitude
m2x_Wnd = mx_Wnd.^2;
% I am Not sure how to get energy spectrum
for i=1:L:nfft-L
E(i) = sum(Xall_Wnd(1:nfft/2+1).^2);
end
% Frequency vector
f = Fs/2*linspace(0,1,nfft/2+1);
% Generate the plot, title and labels.
subplot(2,2,1)
plot(time,X_input);
title('Time Domain')
xlabel('Time(s)')
subplot(2,2,2)
plot(f,m2x_Wnd);
title('Power Spectrum of x(t)');
xlabel('Frequency (Hz)');
ylabel('Normalised Power of fft');
subplot(2,2,3)
plot(f,mx_Wnd);
title('Hamming Window_ Spectrum of x(t)');
xlabel('Frequency (Hz)');
ylabel('Normalised Magunitude of fft');
subplot(2,2,4)
plot(f,E);
title('Energy Spectrum of x(t)');
xlabel('Frequency (Hz)');
ylabel('Energy');
end
Generally you can calculate the spectrum in this way:
h = spectrum.welch('hamming',2048,50);
PSD = psd(h,x(t),'nfft',2048,'fs',Fs);