MATLAB symvar函数如何工作?

时间:2019-05-13 18:03:01

标签: matlab symbolic-math

我阅读了有关symvar函数的文档和帮助,但对于它的工作原理仍然感到困惑,尤其是对于以下示例:

syms x y a
symvar(x + y, 1)

运行此M文件时,得到答案'x'。为什么我得到这个答案?为什么不'y'呢?写为第二个参数的数字1的作用是什么?

1 个答案:

答案 0 :(得分:3)

我猜您在MATLAB Command Window中键入了help symvar,这通常是最好的第一步,但是在这种情况下,您可能会遇到一个小陷阱。这是因为symvaroverloaded function:存在多个副本,被调用的副本取决于传递给它的变量/对象的数据类型/类。通过将which函数与-all选项一起使用,可以查看所有版本。我在R2018a上获得的输出是:

>> which symvar -all
C:\Program Files\MATLAB\R2018a\toolbox\matlab\funfun\symvar.m
C:\Program Files\MATLAB\R2018a\toolbox\curvefit\curvefit\@fittype\symvar.m  % fittype method
C:\Program Files\MATLAB\R2018a\toolbox\symbolic\symbolic\@sym\symvar.m      % sym method
C:\Program Files\MATLAB\R2018a\toolbox\matlab\funfun\@inline\symvar.m       % inline method

请注意...\matlab\funfun中的默认版本,然后是fittypesyminline对象的另外三个版本。当您键入help symvar时,您会得到第一个帮助,这并不是很有帮助,因为您需要重载的sym方法的帮助。为此,您应该输入help sym/symvar,然后会看到类似这样的内容:

 symvar Finds the symbolic variables in a symbolic expression or matrix.
     symvar(S), where S is a scalar or matrix sym, returns a vector sym
     containing all of the symbolic variables appearing in S. The
     variables are returned in lexicographical order. If no symbolic variables
     are found, symvar returns the empty vector.
     The constants pi, i and j are not considered variables.

     symvar(S,N) returns the N symbolic variables closest to 'x' or 'X'.
     If N exceeds the number of variables appearing in S, or equals inf,
     then all variables appearing in S are returned.
     Upper-case variables are returned ahead of lower-case variables.
     If S is a symbolic function the inputs to S are listed in front of the
     other free variables. 

     Examples:
        syms alpha a b x1 y

        symvar(alpha+a+b) returns
         [a, alpha, b]

        symvar(cos(alpha)*b*x1 + 14*y,2) returns
         [x1, y]

        symvar(y*(4+3*i) + 6*j) returns
         y

您还可以使用在线文档获取最新的MATLAB版本:symvar

这清楚表明symvar对符号变量的作用。它将返回在表达式中找到的所有符号变量的向量,将其作为第一个参数传递给它。如果您将第二个自变量指定为数字,则它将最多返回那么多的符号变量,首先选择字母上最接近'x'的那些。