Trouble plotting Fourier Series in MATLAB

539 Views Asked by At

I was wondering if anybody could help me with plotting my Fourier Series in MATLAB. I've had a go at it and I don't believe I have arrived at the correct answer. I've plotted the expanded result fine but I can't seem to plot the result with the $\sum$ in it. I'm attempting to get the 3rd-order approximation for: $$e^{-t}$$

The following is my result which I believe is fine:

$$\frac{sinh(π)}{π} + \frac{2sinh(π)}{π} \sum_{n=1}^3 \frac{(-1)^n}{n^2+1} (cos(nt) + nsin(nt))$$

and the following is my MATLAB code so far:

t = -pi:0.1:0;  
x = exp(-t);   
plot(t,x)  
axis([-6 6 -5 25]) 
hold on
t = 0:0.1:pi;
y = exp(-t);
plot(t,y)
t = -pi:0.1:pi;
f = sinh(pi)/pi;
for n = 1:3
    sinterm = (sin(n*t)*n*(((-1)^n))/(n^2 + 1));
    if n/2 == round(n/2)
        costerm = 0;
    else
        costerm = (cos(n*t)*(((-1)^n))/(n^2 + 1));
    end
    f = f + 2*(sinh(pi)/pi)*(sinterm + costerm);
end
plot(t,f)

If someone could point out an error in my code or fix it up so that my approximation actually works, it would be greatly appreciated.

Thanks

1

There are 1 best solutions below

0
On

I don't really know the background on why looking for Fourier transform for a non-periodic function, but it seems the result you got is what you can really get.

On a separate note, I always find that using anonymous functions in Matlab makes these things a lot easier. With your example:

% original function
f=@(t) exp(-t) 
% approximation function
f_hat=@(t) sinh(pi)/pi+2*sinh(pi)/pi*( (-1/(2)*(cos(t)+sin(t)))... % 1st order
                                     + (1/5*(cos(2*t)+2*sin(2*t)))... % 2nd order
                                     + (-1/10*(cos(3*t)+3*sin(3*t))) ) % 3rd order
% plot and compare
t=-pi:0.01:0; y=f(t); y_hat=f_hat(t);
figure,plot(t,y,'.',t,y_hat,'x')