What is the difference between creating creating functions using function handle and declaring syms?

Viewed 210

It seems that, to create a function f(x,y)=x+y, I can have two approaches.

  1. syms x y; f(x,y) = x+y
  2. f = @(x,y) x+y

They seem very similar, and I do not know whether there are some subtle differences.

1 Answers

Typically, if I need to evaluate the function for inputs or many samples I would opt-in to using the second method (function handles/anonymous functions).

Method 1: Symbolic Functions

This method allows the function to be evaluated at a specific point/value by using the subs(), substitution function. Both plots can be plotted using fsurf().

clear;
syms x y
f(x,y) = x+y;
fsurf(f);

subs(f,[x y],[5 5])

Variants and offsetting of symbolic functions can be done similarly to anonymous functions/function handles with the one caveat of not needing to include the input parameters in the @().

g = f(x,y) + f(x-5,y-5) 
fsurf(g);

Method 2: Anonymous Functions/Function Handles

This method allows you to directly input values into the function f(x,y). I prefer anonymous functions because they seem more flexible.

clear;
f = @(x,y) x+y;
fsurf(f);

f(5,5)

Some cool things you can do is offset and easily add variants of anonymous functions. Inputs can also be in the form of arrays.

x = 10; y = 2;
f(x-5,y-5) + f(x,y)

g = @(x,y) f(x,y) + f(x-5,y-20);
fsurf(g);

Ran using MATLAB R2019b

Related