106 views (last 30 days)

I want to integrate an anonymous function but be able to manipulate it first. For example

f = @(x) [x -x sin(x)];

r = integral (f'*f, 0, 1, 'ArrayValued', true);

This isn't possible. I would have to define a new function but this isn't flexible. Any alternatives to directly manipulate f?

Kye Taylor
on 22 Apr 2013

Try

r = integral (@(x)f(x)'*f(x), 0, 1, 'ArrayValued', true);

Kye Taylor
on 22 Apr 2013

Well, the integral function actually evaluates the function handle many times!

But, to answer your question, each time the function handle g = @(x)f(x)'*f(x) is evaluated by the integral function, the function handle f will be evaluated twice, though this will hardly affect performance.

If you're unconvinced, you could instead define the entire outer product:

g = @(x)[x^2 -x^2 x*sin(x);-x^2 x^2 -x*sin(x);x*sin(x) -x*sin(x) sin(x)^2]

then integrate

integral (g, 0, 1, 'ArrayValued', true);

Mike Hosea
on 22 Apr 2013

MATLAB files can be flexible when they are combined with the use of anonymous functions. Anonymous functions can also be supplied as parameters to anonymous functions. The example given can be handled with simple nesting:

f1 = @(x)[x -x sin(x)]

f2 = @(x)x'*x;

g = @(x)f2(f1(x));

r = integral (g, 0, 1, 'ArrayValued', true);

More cleverness may be required in some cases, I guess. You can extend f2 to accept multiple inputs based on x or nest deeper, constructing what amounts to an evaluation tree to minimize redundant computations. -- Mike

Mike Hosea
on 22 Apr 2013

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!
## 1 Comment

## Direct link to this comment

https://au.mathworks.com/matlabcentral/answers/73119-anonymous-functions-and-integration#comment_144765

⋮## Direct link to this comment

https://au.mathworks.com/matlabcentral/answers/73119-anonymous-functions-and-integration#comment_144765

Sign in to comment.