0
$\begingroup$

I want to solve a system of simple differential equations. At some point I need to solve non-linear system of algebraic equations with Newton method. I would like to efficiently create a right hand side vector using Table[] or similar command. The problem is that the system consists of two equations, so what I need is:

F=Table[
(*do something*)
,{i,1,k}]

but in fact $F$ should have $2k$ entries. For example for $k=5$ Length[F] should return $10$. How to achieve that efficiently? I know I can create different values for odd indexes and even, but then I need additional If[] or to break the whole code into two Table[] executions what I would like to avoid. I could possibly also create two element lists {a,b}, and flatten it at the end... But It still seems quite expensive.

$\endgroup$
2
  • 3
    $\begingroup$ On what basis do you assert that Flatten is expensive? Did you time it? $\endgroup$ Commented Dec 4, 2013 at 20:36
  • 1
    $\begingroup$ If you are looking for alternatives to Flatten you could try Last@Reap[ Do[ Sow[ .. ] , {i,k},{j,2} ] ]. Doubt its faster than Flatten@Table[ ..] though. $\endgroup$
    – george2079
    Commented Dec 4, 2013 at 22:12

1 Answer 1

3
$\begingroup$

Posting this because I was a but surprised by the result..

n = 10^6
Last@Last@Reap[Do[ Sow[2 i + j - 2], {i, n}, {j, 2}]] == Range[2 n] // Timing
-> {3.307221, True}
Table[Unevaluated@Sequence[2 i + 1 - 2, 2 i + 2 - 2], {i, n}] == Range[2 n] // Timing
-> {1.918812, True}
Flatten@Table[ 2 i + j - 2, {i, n}, {j, 2}] == Range[2 n] // Timing
-> {0.093601, True}
Riffle[Table[ 2 i + 1 - 2, {i, n}], Table[ 2 i + 2 - 2, {i, n}]] == Range[2 n] // Timing
-> {0.078001, True}

Note the Riffle approach might really win out depending on how your expression simplifies.

$\endgroup$
3
  • 2
    $\begingroup$ One more example: Table[Unevaluated@Sequence[2 i - 1, 2 i], {i, n}] == Range[2 n] // Timing. It is quite slow, but a bit faster then Reap/Sow. $\endgroup$
    – ybeltukov
    Commented Dec 4, 2013 at 23:13
  • $\begingroup$ nice, added that to the answer for reference.. $\endgroup$
    – george2079
    Commented Dec 5, 2013 at 15:04
  • $\begingroup$ How about Flatten@Table[{2i-1,2i},{i,n}]? $\endgroup$ Commented Dec 5, 2013 at 19:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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