Numerical integration in a loop
15 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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
i=0
t=0:0.01:5;
a=0
for i=1:length(t);
x=(0:0.01:t);
y=@(x)-0.044*cos(omega_11.*x).*exp(-0.266.*(t-x)).*sin(13.29.*(t-x));
z(t)=quad(y,a,x)
end
plz help :)...thanks in advance
0 commentaires
Réponses (2)
Walter Roberson
le 6 Fév 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
x=(0:0.01:t);
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.
2 commentaires
Walter Roberson
le 10 Fév 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)
x=(0:0.01:t(i));
y=@(x)-0.044*cos(omega_11.*x).*exp(-0.266.*(t(i)-x)).*sin(13.29.*(t(i)-x));
z(i)=quad(y,a,x);
Mike Hosea
le 10 Fév 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));
end
2 commentaires
Mike Hosea
le 14 Fév 2014
That's just a newer function you don't have in your version of MATLAB. Try quadgk() instead of integral().
Voir également
Catégories
En savoir plus sur Numerical Integration and Differentiation dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!