Asked by Meva
on 6 Apr 2015

Hi,

Simple que: I have used below and it gave me the error in the question title.

xx=linspace(0,1,101);

Ah4 = ones(1,101);

integral(@(xx) -4*Ah4, 0, xx)

I need to integrate

int_0^x -4 dx

my x should be

xx is x actually and needs to be (0:0.01:1)

Answer by Mike Hosea
on 14 Apr 2015

Accepted Answer

>> help integral

integral Numerically evaluate integral.

Q = integral(FUN,A,B) approximates the integral of function FUN from A

to B using global adaptive quadrature and default error tolerances.

[snip]

So the error message is telling you that the second and third inputs must be scalars, but in your example, the third input is an array 101 elements long. Not sure why you introduced Ah4 there, as this needs to be the size of the argument xx to the integrand, which is a different xx than the one previously defined. We should probably use a different variable name to avoid confusion there. I'll use t. A simple way to do this would be:

y = zeros(size(xx));

for k = 1:numel(xx)

y(k) = integral(@(t)-4*ones(size(t)),0,xx(k));

end

However, if you wanted to do it in one fell swoop, you could do this as a vector-valued integrand, but we need the same scalar limits. So you could transform the problem

int_a^b f(u) du = int_0^1 f(a + t*(b - a))*(b - a) dt

which in this case, since f(u) is the constant -4, which doesn't depend on u, it becomes

int_0^x -4 dx = int_0^1 -4*(x - 0) dt

so

y = integral(@(t)-4*xx,0,1,'ArrayValued',true);

Something you might want to consider for efficiency in the general case (i.e. with difficult integrands, not with this problem, since it is way too easy to integrate, even by hand -- y = -4*xx, no need to call INTEGRAL!), you could take advantage of the fact that int_a^b f(u) du = int_a^c f(u) du + int_c^b f(u) du.

y = zeros(size(xx));

y(1) = 0;

for k = 2:numel(xx)

y(k) = y(k - 1) + integral(@(t)-4*ones(size(t)),xx(k-1),xx(k));

end

Sign in to comment.

Opportunities for recent engineering grads.

Apply Today
## 1 Comment

## Geoff Hayes (view profile)

## Direct link to this comment

https://se.mathworks.com/matlabcentral/answers/196400-a-and-b-must-be-floating-point-scalars#comment_277129

Sign in to comment.