傅里叶级数 - 用Matlab绘制

时间:2014-09-22 17:10:36

标签: matlab plot fft series

这是我的傅立叶级数图的m文件:

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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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