0

What is the difference in defining a function with syms or @ (x)?

For example:

syms f(t)
f(t) = 0.5*cos(280*pi * t) + 0.5 * sin(260*pi * t) + 0.5 * cos(300*pi * t); 

and

f = @ (t) 0.5*cos(280*pi * t) + 0.5 * sin(260*pi * t) + 0.5 * cos(300*pi * t); 

Thanks

Liam F-A
  • 135
  • 11
  • The one is a symbolic expression and the other is not. The symbolic expression can be manipulated symbolically. If you don’t need symbolic manipulation, don’t use symbolic expressions, they are expensive to evaluate. – Cris Luengo Jul 03 '20 at 20:51

1 Answers1

1

Symbolic function

syms f(t)
f(t) = 0.5*cos(280*pi * t) + 0.5 * sin(260*pi * t) + 0.5 * cos(300*pi * t);

defines a symbolic function. This means that there is no loss of precision when using the function. The results are always exact:

>> f(1)
ans =
1

Also, you can apply symbolic operations to the function. For example, you can compute its derivative function, among other operations:

>> g = diff(f)
g(t) =
130*pi*cos(260*pi*t) - 140*pi*sin(280*pi*t) - 150*pi*sin(300*pi*t)

This is a new symbolic function, which can be used normally:

>> g(1/260)
ans =
140*pi*sin(pi/13) - 130*pi + 150*pi*sin((2*pi)/13)

Note how, again, the result is exact. If you want to obtain its numerical value (which will necessarily be an approximation) you can convert to double floating-point representation:

>> double(g(1/260))
ans =
 -84.154882885760415

or, if you need more decimals, you can use vpa:

>> vpa(g(1/260), 50)
ans =
-84.154882885760413712114778738680201384788201830179

Using symbolic functions incurs a cost in efficiency: the code will generally be slower than with standard functions. Besides, they are limited to mathematical operations, whereas standard functions can do many other things, such as dealing with text or files.

Standard, numerical function

f = @ (t) 0.5*cos(280*pi * t) + 0.5 * sin(260*pi * t) + 0.5 * cos(300*pi * t);

defines a standard, numerical function. More specifically, it defines an anonymous function, and then defines f as a handle to that function, with the result that f can be used as the function name.

You can "only" use this function to pass inputs and get outputs as result. Besides, with the default floating-point double data type you may encounter some numerical inaccuracies. For example, f(1) gives

>> f(1)
ans =
   0.999999999999963

instead of the exact result 1.

In contrast with the symbolic case, Matlab doesn't know how to compute its derivative, so in this case you would have to do it numerically (using finite differences), which is an approximation (both because of using finite differences and because of working with floating-point values):

>> t0 = 1/260;
>> h = 1e-9;
>> (f(t0+h)-f(t0))/h
ans =
 -84.154498258826038

Compared with symbolic functions, standard functions are faster (and don't require the Symbolic Toolbox), and as mentioned above, are not limited to mathematical operations.

Luis Mendo
  • 110,752
  • 13
  • 76
  • 147