A function handle can be used to call a function, e.g.
f = @sin;
val = f(1.0);
so why is feval
ever needed?
val = feval(f, 1.0);
When is it useful?
Function to evaluate, specified as a function name or a handle to a function. The function accepts M input arguments, and returns N output arguments. To specify fun as a function name, do not include path information. Invoking feval with a function handle is equivalent to invoking the function handle directly.
Functions provide more flexibility, primarily because you can pass input values and return output values. For example, this function named fact computes the factorial of a number ( n ) and returns the result ( f ). This type of function must be defined within a file, not at the command line.
Evaluating a function means finding the value of f(x) =… or y =… that corresponds to a given value of x. To do this, simply replace all the x variables with whatever x has been assigned. For example, if we are asked to evaluate f(4), then x has been assigned the value of 4.
Specify varargin by using lowercase characters. After any explicitly declared inputs, include varargin as the last input argument . When the function executes, varargin is a 1-by-N cell array, where N is the number of inputs that the function receives after the explicitly declared inputs.
For feval
, the first argument can be a quoted string, giving you more flexibility than a function handle. You could do things like having functions with a base name followed by an index as in fn1
, fn2
, fn3
, and then invoke these dynamically using feval(['fn', num2str(k)], x, y, z);
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With