I want to write a script that reads an input text file that specifies the parameters and then uses them to solve an integral

조회 수: 2 (최근 30일)
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
Gideon Sarpong
Gideon Sarpong 2022년 12월 14일
I improved the code to this and i do not get errors but shows this plot.
[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;
a = w(1);
b = w(2);
y = 0.5;
fx = @(x) a*x-b*x*y;
format long
fx = integral(fx,t,tf,'RelTol',1e-8,'AbsTol',1e-13,'ArrayValued',true);
c = w(3);
d = w(4);
x = 4/3;
fy = @(y) c*x*y-d*y;
format long
fy = integral(fy,t,tf,'RelTol',1e-8,'AbsTol',1e-13,'ArrayValued',true);
figure (1)
plot(fx,'*')
hold on
plot(fy)
Torsten
Torsten 2022년 12월 14일
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".

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

채택된 답변

Fabio Freschi
Fabio Freschi 2022년 12월 16일
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개)

카테고리

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

제품


릴리스

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by