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 个)
madhan ravi
2019-4-24
integral(A1,0,1,'ArrayValued',1)
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 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!