在MATLAB中评估符号表达式

时间:2018-06-27 17:51:30

标签: matlab

我正在尝试评估一个在某些输入值下为无限余弦序列的函数。

编辑:发布图像以描述无限级数的样子 enter image description here

我编写了以下代码以在MATLAB中对其进行描述。

function func = cosfun_hat(a,i)
    syms m x;

    assume(m,'integer');
    assumeAlso(m > 0);

    sum(x) = sqrt(1-a^2)*symsum(sqrt(2)*a^m*cos(i*sym(pi)*x*2^m+1),m,0,Inf);
    func(x) = sum(x);
end

我想评估返回的“函数” func,以获得某些输入范围(如x_in = 0:0.001:1)的数值。

%Trying to evaluate func at x = 2
%In the command window I write
func = cosfun_hat(0.5,2);
func(2)

返回符号表达式:

(2^(1/2)*3^(1/2)*sum((1/2)^m*(exp(- pi*exp(m*log(2))*4*i - i)/2 + exp(pi*exp(m*log(2))*4*i + i)/2), m == 0..Inf))/2

我尝试使用subs来评估表达式:

%In the command window
syms y;
w(y) = func(y);
y = 2;
subs(w);

但是返回相同的符号表达式。我对符号MATLAB很陌生。

谢谢!

编辑根据我尝试过的@NickyMattsson的评论

vpa(func(2)) 

返回表达式的数值。 然而, vpa(func(0.1))返回一个符号表达式:

ans =

1.2247448713915890490986420373529*numeric::sum((1/2)^m*(exp(- (pi*exp(m*log(2))*i)/5 - i)/2 + exp((pi*exp(m*log(2))*i)/5 + i)/2), m == 0..Inf)

使用double(func(0.1))double的相同问题不会返回任何内容,并且会卡住。

2 个答案:

答案 0 :(得分:4)

想出了一种不使用符号MATLAB的方法。

function func = cosfun_hat(a,i,x)
    m = 0;
    sum = zeros(1,length(x));
    sum2 = Inf(1,length(x));
    while max(sum2-sum) > 1e-16
        disp(m);
        sum2 = sum;
        sum = sum + sqrt(1-a^2)*sqrt(2)*a^m*cos(i*pi*x*2^(m+1));
        m = m+1;

    end
    func = sum;
end

总和在100次迭代中收敛。

现在可以了,

%In command window
x_in = -2:0.001:2;
f = cosfun_hat(0.6,2,x_in);
plot(x_in,f);

我得到了情节:

enter image description here

感谢大家的帮助!

答案 1 :(得分:-1)

使用此命令

double(func(2))
相关问题