Anonymous functions and integration

조회 수: 66 (최근 30일)
Jim
Jim 2013년 4월 22일
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?
  댓글 수: 1
Cedric
Cedric 2013년 4월 22일
편집: Cedric 2013년 4월 22일
Either
r = integral (@(x)f(x)'*f(x), 0, 1, 'ArrayValued', true);
or
g = @(x)f(x)'*f(x) ;
r = integral (g, 0, 1, 'ArrayValued', true);
but that's what you call defining a new function I guess.

댓글을 달려면 로그인하십시오.

채택된 답변

Kye Taylor
Kye Taylor 2013년 4월 22일
Try
r = integral (@(x)f(x)'*f(x), 0, 1, 'ArrayValued', true);
  댓글 수: 2
Jim
Jim 2013년 4월 22일
This works, but does it evaluate f(x) twice?
Kye Taylor
Kye Taylor 2013년 4월 22일
편집: Kye Taylor 2013년 4월 22일
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);

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Mike Hosea
Mike Hosea 2013년 4월 22일
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
  댓글 수: 2
Jim
Jim 2013년 4월 22일
That's an elegant solution. I wonder if there is any difference in performance from Kye's answer. I did a basic timing test of the two approaches and there isn't any meaningful difference in computation times.
Mike Hosea
Mike Hosea 2013년 4월 22일
편집: Mike Hosea 2013년 4월 22일
I expect no significant difference on a simple function like this. It should be more valuable if the real f1 is rather expensive to evaluate or if the real f2 involves many uses of the input rather than just a pair. I didn't intend my response to be so much a competing answer to Kye's as a response to your concern with his solution. I probably should have made it a comment under his answer.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Programming에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by