How to solve system of first order ODE's by forming matrix
5 次查看(过去 30 天)
显示 更早的评论
Q:
dy1/dt = 2*y1+5*y2+y3
dy2/dt = 7*y1+9*y2
dy3/dt = 4*y1+y2+3*y3
y1(0) = 0, y2(0)= 0, y3(0) = 0;
i want to plot y1(t), y2(t) and y3(t) waveforms over time 0 to 10sec.
i tried the below code
syms y1(t) y2(t) y3(t)
Y = [y1(t);
y2(t);
y3(t)];
A = [2 5 1;
7 9 0;
4 1 3];
diff(Y, t) = A.*Y;
tspan = [0 10];
Y(0)=zeros(1.,3);
[t, Y] = dsolve(diff(Y, t), tspan, Y(0));
Y1 = Y(:, 1);
plot(t, Y1);
Y2 = Y(:, 1);
plot(t, Y2);
Y3 = Y(:, 1);
plot(t, Y3);
But iam getting an error like this
>> Untitled5
Error using sym/subsindex (line 864)
Invalid indexing or function definition. Indexing must follow MATLAB indexing. Function arguments must be
symbolic variables, and function body must be sym expression.
Error in sym/privsubsasgn (line 1151)
L_tilde2 = builtin('subsasgn',L_tilde,struct('type','()','subs',{varargin}),R_tilde);
Error in sym/subsasgn (line 972)
C = privsubsasgn(L,R,inds{:});
Error in Untitled5 (line 9)
diff(Y, t) = A.*Y;
Anyone please tell where i went wrong. I want to solve with matrices(since my main code have 20 ODE's to solve) only, please suggest me in this way only.
Thanks in advance.
0 个评论
采纳的回答
Wan Ji
2021-8-30
编辑:Wan Ji
2021-8-30
Do not use syms, because without syms, the code runs faster
A = [2 5 1;
7 9 0;
4 1 3];
odefun = @(t,Y)A*Y;
tspan = [0 10];
Y0=zeros(3,1);
[t, Y] = ode45(odefun, tspan, Y0);
Y1 = Y(:, 1);
hold on
plot(t, Y1);
Y2 = Y(:, 1);
plot(t, Y2);
Y3 = Y(:, 1);
plot(t, Y3);
legend('Y1','Y2','Y3')
As the initial conditions are all zero, the final results become zero for Y1 Y2 and Y3
IF you want to use syms
syms y1(t) y2(t) y3(t)
A = [2,5,1;7,9,0;4,1,3];
eq = diff([y1;y2;y3])==A*[y1;y2;y3];
conds = [y1(0)==0; y2(0)==0; y3(0)==0];
[y1,y2,y3] = dsolve(eq,conds)
tspan = 0:0.1:10;
y_1 = eval(subs(y1,t,tspan));
y_2 = eval(subs(y2,t,tspan));
y_3 = eval(subs(y3,t,tspan));
figure(1)
clf
hold on
plot(tspan, y_1);
plot(tspan, y_2);
plot(tspan, y_3);
legend('Y1','Y2','Y3')
Then the result becomes
y1 =
0
y2 =
0
y3 =
0
7 个评论
更多回答(1 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Special Values 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!