绘制符号傅立叶级数

时间:2018-05-04 09:14:20

标签: matlab plot symbolic-math continuous-fourier

我为傅里叶系列编写了代码。这就是我到目前为止所做的:

function FS = FourierSeries(f,degree)

cosCoefficients = zeros(1,degree);
sinCoefficients = zeros(1,degree);

syms x;

a0 = double((1/pi)*int(f,-pi,pi));


for n = 1:degree
    cosCoefficients = cosCoefficients + (1/pi)*int(f*cos(n*x),-pi,pi);
    sinCoefficients = sinCoefficients + (1/pi)*int(f*sin(n*x),-pi,pi);
end

for n = 1:degree
    FS = 0.5*a0 + cosCoefficients.*cos(n*x) + sinCoefficients.*sin(n*x);
end

然后,我还创建了以下函数文件:

function y = func1(x)
syms x
y = (x^2);
end

问题在于,当我尝试绘制func1FS1 = FourierSeries(func1, 4)时,我不断收到错误消息

  

数据必须是数字,日期时间,持续时间或可转换为double的数组。

如何绘制这个傅立叶级数?

2 个答案:

答案 0 :(得分:2)

whos FS1
  Name      Size            Bytes  Class    Attributes

  FS1       1x4                 8  sym   

这告诉您FS1是一个符号函数,需要先进行评估才能绘制它:

FS1 = FourierSeries(func1, 4);
xIDX = -10:0.1:10;
array = zeros(size(xIDX));

for ii = 1:numel(xIDX)
    x = xIDX(ii);
    array(ii) = sum(double(subs(FS1)));
end

figure
plot(array)

enter image description here

subs将符号表达式转换为字符串,前提是工作空间中存在符号变量xdouble然后将字符串转换为实际数字,并且因为FS中有4个术语,我们需要总结这些,这毕竟是傅里叶级数。< / p>

更短,不要用数字进行评估,但要使用MATLAB的内置符号绘图函数fplot

figure
hold on
fplot(func1,'b')
fplot(sum(FS1),'r') % sum over the Fourier components
legend ('func1', 'FS1')

enter image description here

答案 1 :(得分:-3)

我在python中使用sympy进行符号数学

from sympy import *
from sympy.plotting import plot
import matplotlib.pyplot as plt
init_printing(use_unicode= True)

x = symbols('x')

def expr1(k):
    x = symbols('x')
    a0 = (integrate(x,(x,-pi,0))+integrate(pi-x, (x,0,pi)))/(2*pi) 
    expr = a0
    stra = 'a1:'+ str(k)
    strb = 'b1:'+ str(k)
    syma = symbols(stra)
    symb = symbols(strb)
    j = 1
    for i in syma:
        i = (integrate(x*cos(j*x),(x,-pi,0))+
        integrate((pi-x)*cos(j*x),(x,0,pi)))/pi
        expr += i*cos(j*x)
        j+=1
    j = 1
    for i in symb:
        i =  (integrate(x*sin(j*x),(x,-pi,0))+
        integrate((pi-x)*sin(j*x),(x,0,pi)))/pi
        expr += i*sin(j*x)
        j+=1
    return expr
plot(expr1(20),(x,-2*pi,2*pi))

plot of the above function