fourier series matlab

Thread Starter

adrenalina

Joined Jan 4, 2011
78
hello everyone. I made a script in matlab to graph the fourier series of a function, but I am not sure if it is the best way of doing it. it takes a while to calculate not a lot but if I lower the step size to say .01 or increase the number of terms it does take a lot longer. So I am wondering if there is a faster way of doing it. the f(x) is x^2(e^(-x)) from [-3,3]

This is my code
Rich (BB code):
syms an;
syms n;
syms x;
y = sym(0);
L = 3;
inc = .05;
m = -3;

an = int(x^2*exp(-x)*cos(n*pi*x/L),x,-L,L)*(1/L); 
bn = int(x^2*exp(-x)*sin(n*pi*x/L),x,-L,L)*(1/L); 
a0 = int(x^2*exp(-x),x,-L,L)*(1/L); 
y = .5 *a0;

for i=1:25
    
    y = y + subs(an, n, i)*cos(i*pi*x/3) + subs(bn, n, i)*sin(i*pi*x/3); 
    
end

w = [-L:inc:L];

for i=1:length(w)
    w(i) = subs(y, m);
    m = m + inc
end

x = [-L:inc:L];
plot(x,w)
first it calculates an, bn, and a0 with the function int(). In the first for loop it calculates the series to the nth term (n is equal to 25 in this case). so now it has a variable y with only x's no n's. then I allocate space for w which is the y values of the series. according to matlab its faster to allocate the space for a variable instead of adding values to it in the for. in the second for it calculates the y value for the series in increments of .05 for x. at the end it plots x and w.
I'm still a beginner in matlab so any help in making this code quicker and better would be appreciated.
 
Last edited:

Thread Starter

adrenalina

Joined Jan 4, 2011
78
I've been messing with the code and I made it much much faster I got rid of the second for loop since I noticed its not necessary. its faster with an increment in x of .0001 compared to .05 with the old code.

Rich (BB code):
syms an;
syms n;
syms x;
y = sym(0);
L = 3;
inc = .0001;


an = int(x^2*exp(-x)*cos(n*pi*x/L),x,-L,L)*(1/L); 
bn = int(x^2*exp(-x)*sin(n*pi*x/L),x,-L,L)*(1/L); 
a0 = int(x^2*exp(-x),x,-L,L)*(1/L); 
y = .5 *a0;

for i=1:25
    
    y = y + subs(an, n, i)*cos(i*pi*x/3) + subs(bn, n, i)*sin(i*pi*x/3); 
    
end


x = [-L:inc:L];

w = subs(y, x);

plot(x,w)
 
Top