4
$\begingroup$

I'm trying to solve coupled equations by using iteration. There are two functions $G$ and $H$ that I need to find. In the code, G and H are actually lists of numbers. I start by using a simpler solution for G and H and then iterate to get the actual solutions. I have two functions newG[G,H] and newH[G,H] that get the previous $G_{i-1}$ and $H_{i-1}$ as input and give the new functions $G_i$ and $H_i$. When my problem had only one function the easiest way to iterate was to use Nest.

G=seed
steps=1000    
FinalG=Nest[NewG,G,steps]

where NewG is a function that takes the previous G and gives the new function back and steps is just the number of steps in the iteration. Now that I'm working with two variables I have two functions NewG and NewH, but I don't really know how to modify the Nest command to make this work. Any comments are welcome! and please ask if you need more information from me.

$\endgroup$
5
$\begingroup$

You can use Through wrapped in Apply to generalize your Nest command to multiple functions:

(* dummy implementations of newG/newH *)
newG[G[i_], H[i_]] := G[i + 1]
newH[G[i_], H[i_]] := H[i + 1]

(* the actual iteration *)
Nest[Apply[Through[{newG, newH}@##] &], {G[0], H[0]}, 5]
(* {G[5], H[5]} *)

Here, the Apply is used to pass multiple arguments to the functions, and the Through is used to apply multiple functions to the arguments. The chain of evaluations is essentially:

Apply[Through[{newG, newH}@##] &][{G[0], H[0]}]
Through[{newG, newH}@##] &[G[0], H[0]]
Through[{newG, newH}[G[0], H[0]]]
{newG[G[0], H[0]], newH[G[0], H[0]]}
{G[1], H[1]}
| improve this answer | |
$\endgroup$
  • $\begingroup$ Hello, Thanks for your answer! I edited my question to add an important piece of information I had left behind. G and H are lists of numbers. Do you think what you wrote would still work if G and H are lists and not individual numbers? Thanks again! $\endgroup$ – P. C. Spaniel Sep 28 '19 at 23:05
  • $\begingroup$ @P.C.Spaniel the code in the answer should work for any type of arguments - I've just used G[i]/H[i] to demonstrate how it's working $\endgroup$ – Lukas Lang Sep 28 '19 at 23:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.