1
$\begingroup$

I have a grid such as the following, and want to assign the values in the second row to the variable in the first row, but it always fail, can you provide a solution? Thank you!

constant = 
 Grid[{{a, b, c, d, e, f, g}, {1, 2, 3, 4, 5, 6, 7}}, Frame -> All]
constant[[1, 1]] // FullForm
constant[[1, 2]] // FullForm
constant[[1, 1]] = constant[[1, 2]]
a
b
c

The results are:

enter image description here

They are not what I want a=1, b=2... Why?

But if I use {a, b, c, d, e, f, g}={1, 2, 3, 4, 5, 6, 7}, it will succeed.

$\endgroup$
  • 3
    $\begingroup$ Grid is a display wrapper, don't use it to define things as it interferes with everything. Just for display. $\endgroup$ – Roman Jun 6 at 11:20
  • 2
    $\begingroup$ You are modifying constant if you want to set a etc then try Evaluate[constant[[1, 1]]] = constant[[1, 2]] but it will only work when a and friends don\t have values/ $\endgroup$ – Kuba Jun 6 at 11:22
  • $\begingroup$ @Roman, Because I have a lot of constant values used in a program, and the program can be used repeatedly only the constant are different, so I want to find a intuitive way to change the constant, the Grid not only can display the values while expressing their one-to-one correspondence, but also give a easy way to modify their values later. Thank you for your attention! $\endgroup$ – likehust Jun 6 at 12:54
  • $\begingroup$ @Kuba, Your method basically solved my problem, only the constant was damaged which will not display a,b,c,d.... but their values 1,2,3.... However, in general, this is an acceptable answer. Thanks. $\endgroup$ – likehust Jun 6 at 13:16
1
$\begingroup$

As mentioned by @Roman, you shouldn't use display wrappers (such as Grid, MatrixForm, etc) in definitions of anything that you want to use in subsequent calculations.

Aside from that, here are two options:

One is to store the names of the variables as strings.

ClearAll["Global`*"]
vars = {a, b, c, d, e, f, g};
values = {1, 2, 3, 4, 5, 6, 7};
labels = Map[ToString, vars];

Set the variables to their corresponding values:

Thread[Evaluate[vars] = values]

{a, b, c}
(* Out[]= {1, 2, 3} *)

You can then show the grid using the variable names stored in labels.

Grid[{labels, values}, Frame -> All]

enter image description here

Another option is to avoid setting the variables altogether, and use them to construct rules instead.

ClearAll["Global`*"]
vars = {a, b, c, d, e, f, g};
values = {1, 2, 3, 4, 5, 6, 7};
rules = Thread[vars -> values]
(* Out[]= {a -> 1, b -> 2, c -> 3, d -> 4, e -> 5, f -> 6, g -> 7} *)

{a, b, c} /. rules
(* Out[]= {1, 2, 3} *)
Grid[{vars, values}, Frame -> All]

enter image description here

$\endgroup$

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