1
$\begingroup$

I'm using two nested Table to generate data which depend on two parameters, let's say it is temperature and pressure, many times in my code. When I change the temp and pressure values in calculations, I have to manually change it in all of the nested ``Table```. Here's simple example:

Table[Table[temp + press, {temp, 200, 500, 100}], {press, 1, 4}]
(* Out: {{201, 301, 401, 501}, {202, 302, 402, 502}, {203, 303, 403, 
  503}, {204, 304, 404, 504}} *)

Is there any way to define firstly parts of tables {temp, 200, 500, 100} and {press, 1, 4} and just use it as a variable at all tables? Or any other construct that will help me to avoid changing all the parameters?

I've seen such a code a while ago but I cant find this right now.

$\endgroup$

2 Answers 2

3
$\begingroup$

You could try this:

(* somewhere at the beginning of your code *)
Ts = Range[200,500,100];
ps = Range[1,4];

(* somewhere in the middle of your code -- version 1 *)
Table[T+p,{p,ps},{T,Ts}]

(* somewhere in the middle of your code -- version 2 *)
Table[Table[T+p,{T,Ts}],{p,ps}]

This works because one can let iteration variables run over a list, see the documentation for Table.

$\endgroup$
2
  • 1
    $\begingroup$ Of course, adding a temperature and a pressure is not usually a good idea from the point of view of units. $\endgroup$
    – user293787
    Jul 2, 2022 at 18:24
  • 1
    $\begingroup$ Yes, of course, it is just a simple (and silly, as it turns out :) example, I actually solve kinetic ODE. Your answer is really helpful, I used iteration over a list many times but I don't know why I haven't got this idea earlier. Thank You! $\endgroup$
    – Lechuu
    Jul 2, 2022 at 19:58
3
$\begingroup$

You may store the iteration variables in some variables and then insert them using "Evaluate". E.g.:

te = {temp, 200, 500, 100};
pr = {press, 1, 4};
Table[temp + press, Evaluate@te, Evaluate@pr]

(* {{201, 202, 203, 204}, {301, 302, 303, 304}, {401, 402, 403, 
  404}, {501, 502, 503, 504}}*)
$\endgroup$
0

Your Answer

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

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