【问题标题】:Conversion between string and symbolic expression error字符串和符号表达式之间的转换错误
【发布时间】:2017-09-29 21:45:26
【问题描述】:

我一直在探索 Matlab 符号工具箱,为即将到来的决赛做准备。但是,我似乎无法将用户输入的字符串转换为符号表达式,然后将其用于集成。

a = input('Plese enter a = ');
b = input('Please enter b = ');
function1 = input('Please enter the function: ', 's');

syms x eq1 
eq1 = sym(function1);

Integral1 = int(eq1 , x, a, b);
Simpson = 1 / 6 * (b - a) * (subs(eq1 , x, a) + 4 * ...
    (subs(eq1 , x, (a+b)/2))...
    + subs(eq1 , x, b));

fprintf('The value of the integral is %s \n', Integral1);
fprtinf('The aprroximation with simp is %s \n', Simpson);

辛普森是辛普森规则的积分近似值。我得到的错误类似于“转换为'sym'返回MuPAD错误:错误:意外'标识符'”行号将是行

eq1 = sym(function1);

【问题讨论】:

    标签: matlab type-conversion symbolic-math


    【解决方案1】:

    一种方法是使用eval

    function1 = input('Please enter the function: ', 's');
    eq1=eval(function1);
    

    但是您需要将结果转换为双精度才能使用fprintf 显示它们:

    fprintf(''The value of the integral is %s \n', double(Integral1));
    

    【讨论】:

      【解决方案2】:

      从 R2017b 开始,使用str2sym

      >> syms f(x)
      >> function1 = input('Please enter the function: ', 's');
      Please enter the function: sin(x)
      >> f(x) = str2sym(function1)
      f(x) =
      sin(x)
      

      见:https://www.mathworks.com/help/symbolic/str2sym.html

      【讨论】:

        猜你喜欢
        • 2017-01-29
        • 2020-08-11
        • 2013-12-26
        • 1970-01-01
        • 2015-07-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-08-04
        相关资源
        最近更新 更多