# How do I declare and iterate a variable in an ODE driver file?

1 ビュー (過去 30 日間)
Miraculous Mongoose 2019 年 9 月 9 日
I have a pair of function and ode driver files. Currently, all values except initial conditions are declared as variables in the function file.
I would like to iterate on one variable, and check if the result is better than the previous value.
For example,
2. run the ODE,
3. print y(end,3).
4. +0.1 to Ssnh (i.e. Snh_in_1 = 1.1)
5. run the ODE,
6. print new y(end,3).
7. if new y(end,3), > original y(end, 3), repeat from step 1.
8. stop when new y(end,3) less than or equal to previous y(end,3), and report this value of Snh_in_1.
These are my code so far
I can imagine an if loop that might work:
result2 = 2;
result1 = 1;
Ssnh_in_1 = 1;
if result2 >= result1
[t,y]=ode15s(@pha_cont,[0,15],y0);
result1 = y(end,3);
Ssnh_in_1 = Ssnh_in_1 + 0.1;
[t,y]=ode15s(@pha_cont,[0,15],y0);
result2 = y(end,3);
else
disp(Ssnh_in_1)
end
But I have no idea how to pass this variable from the driver into the function file.
How can I do what I want in Matlab? Thanks in advance!

#### 0 件のコメント

サインイン to comment.

### 採用された回答

Torsten 2019 年 9 月 9 日
yold = -Inf;
Ssnh_in_1 = 1;
[t,y]=ode15s(@(t,y)pha_cont(t,y,Ssnh_in_1),[0,15],y0);
ynew = y(end,3);
while yold < ynew
Ssnh_in_1 = Ssnh_in_1 + 0.1;
[t,y]=ode15s(@(t,y)pha_cont(t,y,Ssnh_in_1),[0,15],y0);
yold = ynew;
ynew = y(end,3);
end
disp(Ssnh_in_1)

#### 1 件のコメント

Miraculous Mongoose 2019 年 9 月 9 日
Thank you! learned 2 new things today :)

サインイン to comment.

### その他の回答 (1 件)

Bjorn Gustavsson 2019 年 9 月 9 日
The way I read your ODE-function your Snh_in_1 is the initial value of the second component of y. If so it should be no more difficult than something like this:
Snh_in_1 = 1;
dSnh_in_1 = 0.1;
for i_iter = 1:10
y0 = [a0,Snh_in_1+(i_iter-1)*dSnh_in_1,c0,d0,e0]; % I lost track of how many components you used
[t,y] = ode15s(@pha_cont,[0,15],y0);
results(i_iter,:) = y(end,:);
Results{i_iter,1} = t; % If you've integrated all your ODE's you might just
Results{i_iter,2} = y; % as well save the entire solution - if it doesn't become too big...
end
% Then do the rest of the analysis after all the ODE-integrations
HTH

#### 1 件のコメント

Miraculous Mongoose 2019 年 9 月 9 日
Sorry, the 2nd component of y() is "Snh_1", not "Snh_in_1", which is around line 30 of the function file.
Is there an easy way to adapt your template so that the driver file references "Snh_in_1" in the function file instead?

サインイン to comment.

サインイン してこの質問に回答します。

Translated by