For my own script, I need to combine several functions and finally calculate the integral of the lot. To simplify it, I made a simple problem with the same error:
"Input function must return 'double' or 'single' values. Found 'function_handle'.". The actual code is much larger, has more parameters and because of the size of the function I prefer multiple seperate functions.
a = @(x) x;
b = @(x) a*cos(x);
C = integral(@(x) b,0,5);
I understand the @(x) is not the right way for using the integral-function, because it should have double or single values, as stated in the error. But in what way should I handle this problem to get the right answer out this simple example? (ans = -5,51...)

 채택된 답변

Star Strider
Star Strider 2019년 11월 3일

1 개 추천

Since ‘a’ is a function of ‘x’, call it as a function.
Try this:
a = @(x) x;
b = @(x) a(x).*cos(x);
C = integral(b,0,5)
returning:
C =
-5.51095918785247
Also, since ‘b’ already exists as a function, the extra function handle is not necessary (unless it is a function of several variables, and only integrating with respect to one). In that event, it is still necessary to refer to it as a function:
C = integral(@(x)b(x),0,5)

댓글 수: 2

Jasper Kregting
Jasper Kregting 2019년 11월 3일
I tried this solution within my own script and it works! Thanks a lot.
Star Strider
Star Strider 2019년 11월 3일
As always, my pleasure!

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

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Mathematics에 대해 자세히 알아보기

질문:

2019년 11월 3일

댓글:

2019년 11월 3일

Community Treasure Hunt

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

Start Hunting!

Translated by