3
votes

Here is my m-file for Fourier series plot:

clear
clc
syms n
a0=input('Enter coefficient a0: ');
an=input('Enter coefficient an: ');
bn=input('Enter coefficient bn: ');
a=input('Enter lower boundary: ');
b=input('Enter upper boundary: ');
t=linspace(a,b,10000);
suma=0;
for n=1:10 %% n could be any number, bigger n - better approximation
suma=suma+(subs(an,'n',n).*cos(2.*n.*pi.*t./(b-a))+subs(bn,'n',n).*sin(2.*n.*pi.*t./(b-a)));
end
series=a0+suma;
plot(t,series)
grid

Problem is, it is so slow! What should I change in my code in order to inrease speed?

EDIT: In reference to macduff's comment: Something like this?

clear
clc
a0=input('Enter coefficient a0: ');
an=input('Enter coefficient an: ','s');
bn=input('Enter coefficient bn: ','s');
a=input('Enter lower boundary: ');
b=input('Enter upper boundary: ');
t=linspace(a,b,10000);
suma=0;
for n=1:10000 %% n could be any number, bigger n - better approximation
ebn = evalin('caller',bn);
ean = evalin('caller',an);
suma = suma + (ean.*cos(2.*n.*pi.*t./(b-a)) + ebn.*sin(2.*n.*pi.*t./(b-a)));
end
series=a0+suma;
plot(t,series)
grid
2
Yes, that is what I was getting at, hope it is useful! - macduff
It's so fast now :) Thanks a lot! - etf
Could you check if the code at this clickable link produces the same result as your code? - Divakar
Error using input Undefined function or variable 'n'. - etf

2 Answers

1
votes

I would try and get away from the symbolic toolbox. Try something that has the an and bn expressions input as a string that can be interpreted by Matlab(I'm guessing it is even now). Then every loop, evaluate the string in the caller's workspace.

for n=1:10 %% n could be any number, bigger n - better approximation
  ebn = evalin('caller',bn);
  ean = evalin('caller',an);
  suma = suma + (ean.*cos(2.*n.*pi.*t./(b-a)) + ebn.*sin(2.*n.*pi.*t./(b-a)));
end
0
votes

Something like this?

clear
clc
a0=input('Enter coefficient a0: ');
an=input('Enter coefficient an: ','s');
bn=input('Enter coefficient bn: ','s');
a=input('Enter lower boundary: ');
b=input('Enter upper boundary: ');
t=linspace(a,b,10000);
suma=0;
for n=1:10000 %% n could be any number, bigger n - better approximation
ebn = evalin('caller',bn);
ean = evalin('caller',an);
suma = suma + (ean.*cos(2.*n.*pi.*t./(b-a)) + ebn.*sin(2.*n.*pi.*t./(b-a)));
end
series=a0+suma;
plot(t,series)
grid