Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

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:

(*do something*)

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.

share|improve this question
On what basis do you assert that Flatten is expensive? Did you time it? –  Simon Woods Dec 4 '13 at 20:36
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. –  george2079 Dec 4 '13 at 22:12

1 Answer 1

up vote 3 down vote accepted

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.

share|improve this answer
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. –  ybeltukov Dec 4 '13 at 23:13
nice, added that to the answer for reference.. –  george2079 Dec 5 '13 at 15:04
How about Flatten@Table[{2i-1,2i},{i,n}]? –  Ray Koopman Dec 5 '13 at 19:58

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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