A and B must be floating-point scalars.

조회 수: 9 (최근 30일)
Meva
Meva 2015년 4월 6일
답변: Mike Hosea 2015년 4월 14일
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
Geoff Hayes
Geoff Hayes 2015년 4월 7일
Meva - your third input to the integral function is xx which is an array of 101 elements and so is not the scalar that is required by this function. If zero is your minimum bound then should one be your maximum? What is the function that you are trying to integrate. Please describe the function and the interval over which you are integrating.

댓글을 달려면 로그인하십시오.

채택된 답변

Mike Hosea
Mike Hosea 2015년 4월 14일
>> 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개)

카테고리

Help CenterFile Exchange에서 Mathematics에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by