Many ask me to tackle this problem by making another function(subroutine) of the lines I want to pick out, using
Block,Module,etc
The problem is different here.Notice that Block and Module defines some local variables and calculate the expression given, But here my lines ARE NOT variables, they are commands, so it still won't work by thinking these commands as some function while you might input something to it and create something else. I don't kown, these lines I want to pick out are like a pipe, datas really want to go in and come out, but it's structure isn't that complex as a subroutine maybe? Forgive me for such silly question, but now it seems my code has changed, instead of pick out those lines that I want to use many times at different ODE solvers, now I combine those solvers into one sigle more huge solver, it turns out this way is more sufficient. But thank you for those replied and fine sugestions.Any way, this question still remains open:
How can we pick out a collections of commands, pack them together and call it where ever we want to use it?
Here is the original question: I wrote some functions (my RungerKutta function ),in order to simplify the question,I give an example as below:
RK2op[f_, {x0_, xn_}, y0_, h_] :=
Block[{xold = x0, yold = y0, sollist = {{x0, y0}}, x, y, n, steps,xnew,ynew,xthird,fn,k1},
steps = Round[(xn - x0)/h];
Do[xnew = xold + h;
xthird = xold + 2*h/3;
fn = f [x -> xold, yold];
k1 = f[xthird, yold + fn*2*h/3];
ynew = yold + h*fn/4 + 3*h*k1/4;
sollist = Append[sollist, {xnew, ynew}];
xold = xnew;
yold = ynew, {steps}];
Return[sollist[[steps + 1]]]]
Now if I want to pick out some lines out of this function, and define those lines as a collection, replace those lines by a name, so I can use those collection of commands(lines) as whole, namely I can simply call the name of this "pack" of lines so to make my function look a little cleaner, how can I do it?i.e. I tried:
collection=xnew = xold + h;
xthird = xold + 2*h/3;
fn = f [x -> xold, yold];
k1 = f[xthird, yold + fn*2*h/3];
ynew = yold + h*fn/4 + 3*h*k1/4;
sollist = Append[sollist, {xnew, ynew}];
xold = xnew;
yold = ynew
then I wrote
RK2op[f_, {x0_, xn_}, y0_, h_] :=
Block[{xold = x0, yold = y0, sollist = {{x0, y0}}, x, y, n, steps,xnew,ynew,xthird,fn,k1},
steps = Round[(xn - x0)/h];
Do[collection, {steps}];
Return[sollist[[steps + 1]]]]
But this simply can't help, Can anyone help me on this?(The reason I want to have this collection is because I want to use these lines in other places many times).
collectionas a function with appropriate inputs (i.e. a subroutine), just like what you did withRK2op? – J. M.'s missing motivation Feb 23 '16 at 13:10