0

I have a table form as:

table = {{a, 6}, {b, ff}, {c, 2}}

I want to associate the first element of each pair from the table to the second element of the pair as in:

a=6, b=ff, c=2.

I want the parameters a,b,c to be recognized throughout the program with assigned values. Doing as below, everything is perfect:

a := 6;
a^2 + 5
Clear[a]
Out[2] 41

But in the example below, I failed:

Clear[table, a, b, c]
table = {{a, 6}, {b, ff}, {c, 2}}
z = table[[1, 1]]
z := table[[1, 2]]
a^2 + 5

Out[4]  {{a, 6}, {b, ff}, {c, 2}}
Out[5]  a
Out[6]  5 + a^2

Why this fail?

István Zachar
  • 47,032
  • 20
  • 143
  • 291
rosu_constantin
  • 121
  • 1
  • 6
  • 2
    I don't see why it should work. One way to assign the second element to the first element is Set @@@ {{a, 6}, {b, ff}, {c, 2}}. Now a returns 6, b returns ff and so on. Maybe if you explain why you think it should work, someone could explain why it doesn't. – C. E. Jan 09 '14 at 15:11

2 Answers2

3

This may be considered a duplicate of Assign the results from a Solve to variable(s) which despite different formulation shares the same shortest answer:

Set @@@ {{a, 6}, {b, ff}, {c, 2}}

This may also be related to Reassign values to symbols if you expect to be able to make different assignments to the same Symbols in the same way. I mean that if you attempt a second series of assignments in the same manner it will not work:

Set @@@ {{a, 5}, {b, Pi}, {c, 7/3}}

Set::setraw: Cannot assign to raw object 6. >>

Set::setraw: Cannot assign to raw object 2. >>

An alternative form that will work requires keeping the assignment pairs in Hold:

List @@ Set @@@ Hold[{a, 5}, {b, Pi}, {c, 7/3}];

{a, b, c}
{5, π, 7/3}

Also related:

Mr.Wizard
  • 271,378
  • 34
  • 587
  • 1,371
2

SetDelayed has attribute HoldAll, so your z := table[[1, 2]] assigns the righthand-side to z instead of a. If you really insist on doing your assignment in this programmatic way, use Evaluate and Set:

Clear[table, a, b, c]
table = {{a, 6}, {b, ff}, {c, 2}}

z = table[[1, 1]]
Evaluate[z] = table[[1, 2]]

Or SetDelayed, but then expect a to be recalculated every time in table which leads to a circular definition of a, causing infinite recursion. Hence the Quiet:

Clear[table, a, b, c]
table = {{a, 6}, {b, ff}, {c, 2}}

z = table[[1, 1]]
Evaluate[z] := Quiet@table[[1, 2]]

A more elegant way (as pointed out by Anon) is to use Set and Apply:

Clear[table, a, b, c];
table = {{a, 6}, {b, ff}, {c, 2}};
Set @@@ table
István Zachar
  • 47,032
  • 20
  • 143
  • 291