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

Réponses (2)

John D'Errico
John D'Errico le 24 Avr 2019
Modifié(e) : John D'Errico le 24 Avr 2019
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.

Catégories

En savoir plus sur Function Creation dans Centre d'aide et File Exchange

Produits

Community Treasure Hunt

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

Start Hunting!

Translated by