How to define the variables of a function handle before the function

3 views (last 30 days)
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 Comment
John D'Errico
John D'Errico on 28 Nov 2020
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.)

Sign in to comment.

Answers (1)

Walter Roberson
Walter Roberson on 28 Nov 2020
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.

Categories

Find more on Entering Commands in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!