Error while integrating a piecewise constant function

I defined a function
>> temp = [2;1.5; 0.75; 1.5; 3.75; 0.75; 1.25; .075; 2.0; 1.0; 1.0];
>> A1 = @(x) temp(floor(x*10)+1);
it's a single input single output function. I want to integrate A1(x) from 0 to 1. When I use Matlab's numerical integrator integral. It throws the following error:
>> integral(A1,0,1)
Error using integralCalc/finalInputChecks (line 526)
Output of the function must be the same size as the
input. If FUN is an array-valued integrand, set the
'ArrayValued' option to true.
Just to check if the integral isn't working how it is supposed to be, I defined a dummy function
>> f = @(x) sin(x)
I am able to integrate it properly. I am not sure what's the problem with the function A1(x). I am using Matlab R2018a

답변 (2개)

John D'Errico
John D'Errico 2019년 4월 24일
편집: John D'Errico 2019년 4월 24일
As an alternative to that which Madhan shows, you can make sure the result is of the correct shape.
A1 = @(x) reshape(temp(floor(x*10)+1),size(x));
integral(A1,0,1)
ans =
1.4575
Either way will work. What matters most is to read the error message, and then fix the problem that integral tripped over.

카테고리

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

제품

질문:

2019년 4월 24일

편집:

2019년 4월 24일

Community Treasure Hunt

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

Start Hunting!

Translated by