How to calculate the integral of the complicated functions of function handles in a cell?

조회 수: 5 (최근 30일)
Hi, I stuck for two days. I don't know how to calculate the integral of the sum of function handles in a cell. Please see the below examples:
f{1} = @(x) x;
f{2} = @(x) x^2;
g = @(x) sum(cellfun(@(y) y(x), f));
integral(@(x) g, -3,3);
Error: Input function must return 'double' or 'single' values. Found 'function_handle'.
PS: please don't change the formula, because this is just an example. My real problem is far more complicated than this. It has log and exp of this sum (integral(log(sum), -inf, inf)). So I can't break them up to do the integral individually and sum the integrals.I need to use sum(cellfun). Thank you.
Version: Matlab R2012a
Can anyone help me? Really appreciate.
  댓글 수: 2
Patrik Ek
Patrik Ek 2014년 4월 1일
편집: Patrik Ek 2014년 4월 1일
integral(f{1}+f{2}) = integral(f{1}) + integral(f{2}). This is a fundamental theorem of mathematics.
smashing
smashing 2014년 4월 1일
Hi Patrik,
Thanks for the tip. As I said, my problem is comlicated than this example. It is not a sum, it has log and exp. So I can't break them up to do the integral individually and sum the integrals.

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

채택된 답변

Azzi Abdelmalek
Azzi Abdelmalek 2014년 4월 1일
f{1} = @(x) x;
f{2} = @(x) x.^2;
g=@(x) f{1}(x)+f{2}(x)
integral(@(x) g(x), -3,3)
  댓글 수: 3
Azzi Abdelmalek
Azzi Abdelmalek 2014년 4월 1일
편집: Azzi Abdelmalek 2014년 4월 1일
Maybe there is better. for the moment I have one solution using eval
f{1} = @(x) x;
f{2} = @(x) x.^2;
n=numel(f)
d=['g=@(x)' sprintf('f{%d}(x)+',1:n)]
d(end)=[]
eval(d)
integral(@(x) g(x), -3,3)
smashing
smashing 2014년 4월 1일
편집: Image Analyst 2014년 4월 1일
This is great! I think this is the solution I am looking for. Thanks Azzi.

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

추가 답변 (1개)

Sean de Wolski
Sean de Wolski 2014년 4월 1일
편집: Sean de Wolski 2014년 4월 1일
Here's a method that scales:
f{1} = @(x) x;
f{2} = @(x) x.^2;
f{3} = @(x) exp(x)-log(x);
I = sum(cellfun(@(fun)integral(fun,-3,3),f))
Instead of using cellfun to evaluate the functions, use it to evaluate the integral and sum the integrals as Patrik suggested above.
Note you need to vectorize the functions (. before /*^)
  댓글 수: 3
Sean de Wolski
Sean de Wolski 2014년 4월 1일
Huh?
cellfun(@(fun)integral(fun,-3,3),f)
Evaluates the integral over the range for each function in funs. Do with this info as you wish!
Azzi Abdelmalek
Azzi Abdelmalek 2014년 4월 1일
Smashing, you have to be clear, your question was about the sum. If there is something else, please edit your question and make it precise.

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

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by