问题
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
回答1:
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
回答2:
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
来源:https://stackoverflow.com/questions/25979541/fourier-series-plot-in-matlab