Numerical integration in a loop

47 views (last 30 days)
Muhammad Irfan
Muhammad Irfan on 6 Feb 2014
Commented: Mike Hosea on 14 Feb 2014
Hi there,
I have a problem integrating numerically using the 'for' loops I want to integrate a function for different upper limits. The upper limit is also an independent variable in the function. you might understand the steps from my code below
I want to evaluate y for different t and x is the limits of the integration function
for i=1:length(t);
plz help :)...thanks in advance

Answers (2)

Walter Roberson
Walter Roberson on 6 Feb 2014
The function you feed in ("y" in this case) is using a vector in t that is not necessarily the same size as the "x" that is being passed in. The documentation indicates,
The function y = fun(x) should accept a vector argument x and return a vector result y, the integrand evaluated at each element of x.
but in your code if a single x were passed in, a vector of length length(t) would result, and if the length of the x that quad() chooses to pass in happens to be the same as length(t) then you are okay, but any other length(x) that quad chooses to pass in will generate an error in subtracting x-t
Also notice that you have
but you have created t as a vector. You are going to get a warning (or error) from trying to use a vector as the upper limit of a ":" operation. Did you perhaps want t(i) as the upper limit on x ?
But that x is not being used in the "y=" because x in that assignment refers to the anonymous parameter (x) for the @ function.
That leaves the vector x being passed in as the third parameter of quad, which is the "b" parameter. The "b" parameter is required to be a scalar, not a vector.
You have too many poorly defined behaviours to guess the code that would be appropriate for you.
You should be considering switching to integral2() anyhow.
Walter Roberson
Walter Roberson on 10 Feb 2014
Yes, inside the "for i" loop, in your x and y lines where you refer to t, you should instead refer to t(i). In your next line where you assign to z(t) you should instead assign to z(i)

Sign in to comment.

Mike Hosea
Mike Hosea on 10 Feb 2014
Is this what you mean?
omega_11 = pi; % or whatever
t = 0:0.01:5;
Q = zeros(size(t)); % Preallocate Q for the sake of efficiency.
for k = 1:length(t)
y = @(x)-0.044*cos(omega_11.*x).*exp(-0.266.*(t(k)-x)).*sin(13.29.*(t(k)-x));
Q(k) = integral(y,0,t(k));
Mike Hosea
Mike Hosea on 14 Feb 2014
That's just a newer function you don't have in your version of MATLAB. Try quadgk() instead of integral().

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!