# A and B must be floating-point scalars.

25 views (last 30 days)

Show older comments

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)

##### 1 Comment

Geoff Hayes
on 7 Apr 2015

### Accepted Answer

Mike Hosea
on 14 Apr 2015

>> 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

##### 0 Comments

### More Answers (0)

### See Also

### Categories

### Community Treasure Hunt

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

Start Hunting!