I'm new to Mathematica, so I don't really know, how do what I want, and I don't even know how to google it.
Doing one Mathematica task for my supervisor, I faced the following problem. I need to write a function with such a syntax:
f[{{var1, val1}, {var2, val2}, ..., {varn, valn}}]
Here $var_i$ is a variable and $val_i$ is a value, which will be assigned to this variable. So this functions is a "parallel" analogue of the function Set[]. $var_i$ has already its value, and it can be evaluated (but it's not what I want).
Number of variables $n$ can vary.
Apparently, I need to set Hold attribute for $f$, but what should I do next? The first thing I've tried to do was just f[l_] := l[[All, 1] = l[[All, 2]]
, but it didn't worked due to some part assignment restrictions.
But if I try to extract variables like vars = l[[All, 1]]
and than do vars = l[[All, 2]]
, it doesn't work too, because vars
just become replaced with values from l[[All, 2]]
.
I know, I must use Hold[] and Unveluated[] somehow, but I don't know how to apply them here.
P.S. The problem I've really faced is sligtly different: I want to build function, which argument is {{var1, a1, b1, n1}, ...}
and which will iterate over $var_i$ from $a_i$ to $b_i$ with step $n_i$. I try to implement "parallel" Set[] first, because of its simplicity.
P.S.S. Sorry for my English, it's not my native language.
Answer
For the simple case where your Symbols (variables) do not already have assignments you do not even need a new function as you may simply use Set @@@
:
Set @@@ {{var1, "a"}, {var2, "b"}, {var3, "c"}};
{var1, var2, var3}
{"a", "b", "c"}
If the question is why doesn't l[[All, 1] = l[[All, 2]]
work see:
(This might be considered a duplicate question.)
If the Symbols already have assignments you will need a structure that will keep them unevaluated.
For example:
new = Hold[{{var1, "x"}, {var2, "y"}, {var3, "z"}}];
Apply[Set, new, {2}] // ReleaseHold;
{var1, var2, var3}
{"x", "y", "z"}
I think you will find these Q&As relevant:
Unfortunately I don't understand your P.S. problem description so I cannot address that yet.
Comments
Post a Comment