2014-09-22 93 views
2

这里是傅里叶级数的情节我的M-文件:傅里叶级数 - 情节在Matlab

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 

问题是,它是如此之慢!为了提高速度,我应该在代码中更改哪些内容?

编辑:在参考macduff的评论: 这样的事情?

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 
+0

是的,这就是我所期待的,希望它有用! – macduff 2014-09-22 19:56:02

+0

现在速度如此之快:)非常感谢! – etf 2014-09-22 20:43:58

+0

您可以检查代码[在此可单击的链接](http://pastebin.com/DWrGPy6q)是否与您的代码产生相同的结果? – Divakar 2014-09-25 17:07:42

回答

1

我会尝试摆脱符号工具箱。尝试使用输入为anbn的表达式作为可由Matlab解释的字符串(我猜测它现在还是)。然后每个循环,评估调用者工作区中的字符串。

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

是这样的吗?

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