1
$\begingroup$

I would like to assign values from a list l to variables g1, g2, g3, ....

The list: l=Table[(i^2-10*i)/2,{i,1,10}].I would like to assign g1 to the first element of the list l[[1]] and so on using a loop.

g1=l[[1]];
g2=l[[2]];
g3=l[[3]];
...

ClearAll["Global`*"]

l = Table[(i^2 - 10*i)/2, {i, 1, 10}]

(*{-(9/2), -8, -(21/2), -12, -(25/2), -12, -(21/2), -8, -(9/
  2), 0}*)

Do[Symbol["g" <> ToString[i]] = l[[i]], {i, 1, 10}]

How to do it correctly?

$\endgroup$
4
  • 3
    $\begingroup$ Based on your last three questions, it appears that you're trying to do some computations with lists of things, and you think you need variables to represent each thing. Or something along those lines. Maybe if you just told us the problem you're trying to solve, we could give you good advice. I'm starting to feel bad about answering your specific questions, because they will ultimately lead you to bad programming practices. $\endgroup$
    – lericr
    May 18 at 16:41
  • 1
    $\begingroup$ Related: mathematica.stackexchange.com/q/274713/7936 $\endgroup$
    – evanb
    May 18 at 17:04
  • $\begingroup$ @lericr, thanks a lot! Yes, you're right, it's worth setting variables more obviously. $\endgroup$
    – Mam Mam
    May 18 at 17:29
  • $\begingroup$ @evanb, thanks for the link! $\endgroup$
    – Mam Mam
    May 18 at 17:29

1 Answer 1

4
$\begingroup$

This question is very likely an XY problem.

I'd say the "correct" way is to avoid symbol construction through strings, and go with indices instead. Using a delayed assignment,

Clear[g];
g[i_Integer /; 1 <= i <= Length[l]] := l[[i]]
g[___] = Indeterminate;

or, if you don't care about error checking,

Clear[g];
g[i_] := l[[i]]

You can use g[5] instead of your g5, for example, without affecting calculations.

$\endgroup$
5
  • $\begingroup$ Thanks! But how to set such variables g[5] in a function f? I mean for example f[g[5]_]:=g[5]^2 $\endgroup$
    – Mam Mam
    May 18 at 16:34
  • 1
    $\begingroup$ Just say something like f[x_]:=g[x]^2? $\endgroup$
    – evanb
    May 18 at 17:06
  • 1
    $\begingroup$ Or, just l^2, even. $\endgroup$
    – evanb
    May 18 at 17:06
  • 2
    $\begingroup$ You need to learn more about what variables and patterns are. As @evanb says, define f[x_] = x^2 and then call f[g[5]] because it will substitute the pattern x_ with the argument g[5]. There is really no need to define a new function f for every variable you have. $\endgroup$
    – Roman
    May 18 at 17:40
  • $\begingroup$ @Roman, thanks! $\endgroup$
    – Mam Mam
    May 18 at 18:15

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.