What are the advantages and differences of using a symbolic function as opposed to a function handle?

I am learning to use MATLAB and have found that a function can be created either as symbolic or as a handle. How do I know which one is better to use?

 Accepted Answer

Symbolic expressions are useful if you want to do symbolic computation i.e. get the answer in the form of a general expression, instead of a number. Whereas function handles are useful if you want to solve a numeric problem, in which you want the final answer and don't care about the general form of the solution.
For example, consider a system of two variables
eq1 = a1*x + a2*y == b1;
eq2 = a3*x + a4*y == b2;
solution = solve([eq1, eq2], [x, y]);
solution.x
solution.y
solution.x = -(a2*b2 - a4*b1)/(a1*a4 - a2*a3)
solution.y = (a1*b2 - a3*b1)/(a1*a4 - a2*a3)
This type of general expression is not possible with function handle. Consider another example
syms x
result = int(sin(x))
result =
-cos(x)
Give you the actual expression of the integration. Not just the numeric result. For such type of calculation, you will definitely need symbolic expressions.
You can also use symbolic toolbox for numeric results for example
syms x
result = int(sin(x), x, 0, pi)
But symbolic calculations are slow as compared to the equivalent calculation with the function handle. For example
f = @(x) sin(x)
result = integral(f, 0, pi)
result =
2.0000
The time for function handle version is
Elapsed time is 0.010003 seconds.
whereas for symbolic version
Elapsed time is 0.068826 seconds.
So it depends on what you are trying to do, whether to use a symbolic expression or function handle.

5 Comments

"But numeric calculations are slow as compared to the equivalent calculation with the function handle"
@Ameer Hamza: I think you meant to write "But symbolic calculations are slow ...".
It is also worth noting that many problems cannot be solved symbolically, but numeric solutions or approximations may be possible.

Sign in to comment.

More Answers (0)

Categories

Tags

Asked:

on 25 May 2018

Commented:

on 11 Jul 2021

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!