for varying values of c by combining two anonymous functions:
g = @(c) (integral(@(x) (x.^2 + c*x + 1),0,1));
Here is how to derive this statement:
1
Write the integrand as an anonymous function,
@(x) (x.^2 + c*x + 1)
2
Evaluate the function from zero to one by passing the function handle to integral,
integral(@(x) (x.^2 + c*x + 1),0,1)
3
Supply the value for c by constructing an anonymous function for the entire equation,
g = @(c) (integral(@(x) (x.^2 + c*x + 1),0,1));
The final function allows you to solve the equation for any value of c. For example:
g(2)
ans =
2.3333
Functions with No Inputs
If your function does not require any inputs, use empty parentheses when you define and call the
anonymous function. For example:
t = @() datestr(now);
d = t()
d =
26-Jan-2012 15:11:47
Omitting the parentheses in the assignment statement creates another function handle, and does not
execute the function:
d = t
d =
@() datestr(now)
Functions with Multiple Inputs or Outputs
Anonymous functions require that you explicitly specify the input arguments as you would for a
standard function, separating multiple inputs with commas. For example, this function accepts two
inputs, x and y:
myfunction = @(x,y) (x^2 + y^2 + x*y);
x = 1;
y = 10;
z = myfunction(x,y)
z = 111
20 Function Basics
20-22
Précédent

- 730/1450

Suivant