Function functions refer to functions that have other function names or handles as input parameters.
For example, MATLAB has a function called fzero. This function is used to find the independent variable for which the function value passed to it is 0. For instance, the statement fzero(‘cos’, [0 pi]) can determine when cos(x) is 0 in the interval [0, pi]. The statement fzero(‘exp(x) – 2’, [0 1]) can determine when the function exp(x) – 2 is 0 in the interval [0, 1].
>> fzero('cos',[0 pi]) % Find the x that makes the function value of cos x zero in the interval 0 to pi
ans =
1.5708
>> fzero('exp(x) - 2',[0 1])
ans =
0.6931
In MATLAB, there are two specialized functions eval and feval that are key to handling function functions.
The function eval evaluates a string as if it were typed in the command window. This function allows MATLAB to construct executable statements during execution. The syntax for the function eval is:
eval(string)
For example:
>> x = eval('sin(pi/4)') % Calculate the value of sin(x) at pi/4
x =
0.7071
The following example constructs a string and evaluates it using the function eval:
x = 1;
str = ['exp(' num2str(x) ') - 1'];
res = eval(str)
In this case, the content of the variable str is the string ‘exp(1) – 1’, and eval computes the result as 1.7183.
The function feval computes the value of a named function defined by an M-file at specified input values. The syntax for the function feval is
feval(fun,value)
For example, to compute sin(x) at x = pi/4:
>> x = feval('sin',pi / 4)
x =
0.7071
Summary:
- fzero is used to find the zeros of a function within a specified interval.
- feval is used to compute the value of a function at a specified point. The calling form is:feval(fun,value)
- eval is used to compute the value of a function at a specified point. The calling form is:eval(string)
Happy learning~~