Fourier series - Plot in Matlab

喜你入骨 提交于 2019-12-11 02:32:01

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!