Using ode45 to solve odes from a matrix

85 次查看(过去 30 天)
This is the code I currently have. It works however I have had to manually input the four odes. (Line 8)
My question is, what code can I use to automate this part by using a matrix and a vector of y(i) variables?
The matrix would be [-f1 f1 0 0; 0 -f2 f2 0; 0 0 -f3 f3; v 0 0 -v]
Thank you!
%=====fx represents transition rate for degredation to next state=====
f1=0.5;
f2=0.5;
f3=0.2;
v=0;
%=====Sets the ordinary differential equations as a vector=====
f = @(t,y)[-f1*y(1)+v*y(4); -f2*y(2)+f1*y(1); -f3*y(3)+f2*y(2); f3*y(3)-v*y(4)];
%=====Sets time period=====
tspan = [0 30];
%=====Sets the initial state conditions as a vector=====
y0 =zeros(4,1);
y0(1) = 1;
%=====Calls the integrator=====
[t, y] = ode45(f,tspan,y0);
%=====Plots the results=====
plot(t,y(:,1),t,y(:,2),t,y(:,3),t,y(:,4))
legend('State 1','State 2','State 3','State 4','Location','best')
title('Probability of being in each state at time t.')

采纳的回答

James Tursa
James Tursa 2020-3-23
编辑:James Tursa 2020-3-23
F = [-f1 f1 0 0; 0 -f2 f2 0; 0 0 -f3 f3; v 0 0 -v].';
f = @(t,y) F * y;

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Ordinary Differential Equations 的更多信息

产品


版本

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by