0
$\begingroup$

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?

$\endgroup$
  • 2
    $\begingroup$ 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. $\endgroup$ – C. E. Jan 9 '14 at 15:11
3
$\begingroup$

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:

$\endgroup$
  • $\begingroup$ Thank you very much for your answer. I'll keep in mind the problems that arise from reassign symbols. $\endgroup$ – rosu_constantin Jan 10 '14 at 9:01
2
$\begingroup$

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
$\endgroup$
  • $\begingroup$ Thank you very much for your proposed solution which helped me completely. Very elegant indeed, with Set and Apply $\endgroup$ – rosu_constantin Jan 10 '14 at 8:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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