How to populate a table with results from a while function

How to populate a table with results from a while function



Does anybody know how to save the intermediate results inside a while function in a table?
Here is my code. I would like to save the x,y,counter values in a table in every step that while takes. Thank you!


counter = 0;
While[counter < 5,
counter = counter + 1;
sol = NSolve[2 x + y - counter == 0,
3 y + 5 x - 2 counter == 0, x, y];
]




4 Answers
4


counter = 0;
sol = ;
While[counter < 5, counter = counter + 1;
AppendTo[sol, Flatten[counter, x, y /.
NSolve[2 x + y - counter == 0, 3 y + 5 x - 2 counter == 0, x, y]]]]

sol



1, 1., -1., 2, 2., -2., 3, 3., -3., 4, 4., -4., 5, 5., -5.



or


counter = 0;
sol2 = ConstantArray[0, 5];
While[counter < 5, counter = counter + 1;
sol2[[counter]] = Flatten@counter, x, y /.
NSolve[2 x + y - counter == 0, 3 y + 5 x - 2 counter == 0, x, y]]
sol2



1, 1., -1., 2, 2., -2., 3, 3., -3., 4, 4., -4., 5, 5., -5.



Use Sow and Reap :


Sow


Reap


counter = 0;
Reap @ While[counter < 5, counter = counter + 1;
sol = NSolve[2 x + y - counter == 0,
3 y + 5 x - 2 counter == 0, x, y];
Sow[x, y, counter /. sol]]



I think other answer take your question too literally. You do not really need While. IMHO Mathematica way of solving this is to use Table.


While


Table



Assuming, that your equation always gives a single solution:


Table[
x, y, counter /.
First@NSolve[2 x + y - counter == 0,
3 y + 5 x - 2 counter == 0, x, y], counter, 5] // TableForm



enter image description here



To reach the same end, as you mentioned Table (a digression: if you know Python, you can compare Wolfram's Table with its list comprehensions, which is attached with more conciseness and readability.), the most direct method is just to use it:


Table


Table


Table[
Append[
NSolve[2 x + y - counter == 0, 3 y + 5 x - 2 counter == 0, x, y],
counter
],
counter, 4
]




x -> 1., y -> -1., 1, x -> 2., y -> -2., 2,
x -> 3., y -> -3., 3, x -> 4., y -> -4., 4





$begingroup$
Using Append you abuse the list of solutions from NSolve. I would make a NSolve,counter instead of Append[NSolve,counter].
$endgroup$
– Johu
Sep 8 '18 at 11:44


Append


NSolve


NSolve,counter


Append[NSolve,counter]



Thanks for contributing an answer to Mathematica Stack Exchange!



But avoid



Use MathJax to format equations. MathJax reference.



To learn more, see our tips on writing great answers.



Required, but never shown



Required, but never shown




By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

Edmonton

Crossroads (UK TV series)