简体   繁体   中英

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

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

  1. syms xy; 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM