How to define the variables of a function handle before the function
이전 댓글 표시
Hello I am trying to get this to work by defining S as y(1) before putting it in S,I,R then F.
Please let me know what is the issue, It was working but i changed something and it doesn't work anymore.
It gives me this error:
Unrecognized function or variable 'y'.
Error in Sc (line 14)
S = y(1)
B=0.02818;
L=0.00098;
h=1;
t_max=5;
t_span = (0:h:t_max);
S_0=2782000
I_0=1;
R_0=0;
y0 = [S_0;I_0;R_0];
N = S_0+I_0+R_0
S = y(1)
I = y(2)
R = y(3)
S_t = - (B*I*S)/N
I_t = (B*I*S)/N - L*I
R_t = L*I
F = @(t,y) [ (B*y(2)*y(1))/N ; (B*y(2)*y(1))/N ;-L*I];
[t,y]= ode45(F,t_span,y0);
댓글 수: 1
John D'Errico
2020년 11월 28일
Regardless of what you had working, you cannot alias variables together, so that when one changes, the other also changes. (Ok, not easily, you could possibly do it with a custom class. Nasty code though, and just pleading for bugs.)
답변 (1개)
Walter Roberson
2020년 11월 28일
B=0.02818;
L=0.00098;
h=1;
t_max=5;
t_span = (0:h:t_max);
S_0=2782000
I_0=1;
R_0=0;
y0 = [S_0;I_0;R_0];
N = S_0+I_0+R_0
S = @(y) y(1)
I = @(y) y(2)
R = @(y) y(3)
S_t = @(y) - (B*I(y)*S(y))/N
R_t = L*I(y)
I_t = @(y) (B*I(y)*S(y))/N - R_t(y)
F = @(t,y) [ -S_t(y); I_t(y) + R_t(y); -R_t(y)];
[t,y]= ode45(F,t_span,y0);
This will have notably worse performance than your existing F definition, due to the extra layers of function calls.
If you want to define your ode function in expressions that are more clear than your existing F, then I recommend using the Symbolic Toolbox to express them, and follow the workflow in the first example of odeFunction() to convert them for numeric use.
카테고리
도움말 센터 및 File Exchange에서 Ordinary Differential Equations에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!