问题描述
在Matlab中使用symfun和匿名函数有什么区别?哪一个更好,即更快?看起来,我可以同时使用符号和实数。
功能符号数学工具箱,它执行完全这一点,并适用于合理缩放功能(但这里是 b
$ b
请注意,虽然您可以使用公式定义匿名函数,如 f = @(x)3 * x ^ 2-2
,这实际上会定义一个数字函数,它返回给定数字输入的值,例如 f(3)
。如果您想要计算公式,请使用数字函数。符号数学应该保留给那些无法用基本数字特征精确求解的情况,比如计算多元标量场的精确梯度。
What is the difference between using a symfun and an anonymous function in Matlab? Which one is better i.e. faster? It seems like, I can use both for symbolic and real numbers.
Here they discuss the difference between inline and anonymous functions, but don't mention symfun.
Basic MATLAB functionality is designed for numerical calculations, i.e. working with floating-point numbers. By default MATLAB variables and functions are numeric, and this is why in your linked discussion only inline and anonymous functions are compared.
However, using the Symbolic Math Toolbox one may use symbolic expressions and functions. This can be very useful for tackling mathematical problems such as exact differentiation, integration, working with arbitrary-precision arithmetic, or solving equations. However, the symbolic engine is designed to be smart, not to be fast (after all, sooner or later the symbolic engine must perform the evaluation of the function, but MATLAB was designed to be efficient with numerical problems). Whenever possible, one should prefer numerical MATLAB functions, especially those can often be extended to work in a vectorized way, along array inputs to provide array output.
When facing a mixed problem (needing symbolic math, but also computation-expensive evaluation of the results), it might be most practical to solve your initial problem in a parametric (symbolic) way once, then to use the very last result by turning it into an appropriate numerical function. You should have a look at the matlabFunction
function of the Symbolic Math Toolbox, which performs exactly this and works quite well for reasonably scaled functions (but here's a counterexample).
Note that while you can define an anonymous function using a formula, as in f=@(x) 3*x^2-2
, this will actually define a numeric function which returns a value for given numeric inputs such as f(3)
. If you have the formula in your hand which you want to compute, always use a numerical function. Symbolic math should be reserved for cases which can not be solved exactly by basic numerical features, such as computing the exact gradient of a multivariate scalar field.
这篇关于matlab symfun vs匿名函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!