matlab symfun vs anonymous function

一笑奈何 提交于 2019-12-24 00:31:29

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/33587313/matlab-symfun-vs-anonymous-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!