I want to write a script that reads an input text file that specifies the parameters and then uses them to solve an integral
1 vue (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Gideon Sarpong
le 14 Déc 2022
Réponse apportée : Fabio Freschi
le 16 Déc 2022
I want to write a script that reads an input text file that specifies the parameters:
a:1
b:2
c:3
d:4
x0:1
y0:1
tf:25.
Then integrate a system of equations given the parameters read from the input text file. Sytem should be integrated from t=0 to t=tf. After plot x(t) and y(t) in a single graph.
This is what I did. It gives me errors. Kindly tell me what i am doing wrong and how to solve the question. Thanks.
[q,w] = readvars('variables.txt');
a = w(1);
b = w(2);
c = w(3);
d = w(4);
x0 = w(5);
y0 = w(6);
tf = w(7);
t = 0;
x = linspace(t,tf,25);
fx = @(x,y) a*x-b*x*y;
fy = @(y,x) c*x*y-d*y;
x = linspace(t,tf,25);
for i = 1:length(x)
fx(i)= integral(@(x)(fx(x,y)),t,x(i));
end
y = linspace(t,tf,25);
for k = 1:length(y)
fy(k)= integral(@(y)(fy(y,x)),t,y(k));
end
figure (1)
plot(fx)
plot(fy)
3 commentaires
Torsten
le 14 Déc 2022
I can only repeat: you can't use "integral" to solve differential equations that depend in the dependent variable.
You must use one of the ode integrators or try "dsolve".
Réponse acceptée
Fabio Freschi
le 16 Déc 2022
As suggested by @Torsten your problem is a system of first order ODEs and you must use a ODE integrator. Try this
clear variables, close all
% your params (you can instead load here your file)
a = 1;
b = 2;
c = 3;
d = 4;
x0 = 1;
y0 = 1;
tf = 25;
% define the system of ODE as anonymous function.
% The vector variable is here X, with X(1) = x, X(2) = y
odeFun = @(t,X)[a*X(1)-b*X(1)*X(2); c*X(1)*X(2)-d*X(2)];
% initial value
X0 = [x0; y0];
% time interval
tSpan = [0 tf];
% solution with ODE45
[t,X] = ode45(odeFun,tSpan,X0);
figure
plot(t,X)
xlabel('time');
legend('x','y')
0 commentaires
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Ordinary Differential Equations 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!