I have these 6 random walks of size 100 generated into a list:

x = Table[
   Flatten@NestList[0.1 + # + RandomVariate[NormalDistribution[], 1] &,0, 99], 

Now I'd like to extract each random walk (each row) from this matrix and automatically name them x1, x2 , ... , x6.

How can I do that? Thanks.

  • $\begingroup$ closely related: How do you programatically load data into symbols? $\endgroup$ – Kuba Oct 13 '16 at 19:39
  • 1
    $\begingroup$ var = Table[Unique["x"], 6];var = x can help? $\endgroup$ – yode Oct 13 '16 at 19:50
  • 1
    $\begingroup$ MapIndexed[ Set[Evaluate[Symbol["x" <> IntegerString[First@#2]]], #1] &, x] $\endgroup$ – Jason B. Oct 13 '16 at 19:51
  • 1
    $\begingroup$ So the question is fine, but why do you want to do this, rather than just using x[[1]], x[[2]], etc.? It just seems to clutter the name-space without much gain. In fact, you lose something by not being able to operate on all of the lists at the same time (by using Table or Map or ...). $\endgroup$ – march Oct 13 '16 at 21:42
  • $\begingroup$ Well in this particular application, you're right, it would be better to just use Part[], but in some cases, I need to import several variables at once, so naming them is more practical then having to remember their "id". $\endgroup$ – EBassal Oct 13 '16 at 22:11

The direct method would be as follows:

{x1, x2, x3, x4, x5, x6} = 
  Table[Flatten@NestList[0.1 + # + RandomVariate[NormalDistribution[], 1] &,
     0, 99], 6]

To automate this process for longer tables, you can use this function to do the same thing:

setRows[s_String, m_List] := 
  With[{vars = s <> # & /@ IntegerString@Range@Length@m}, 
    Clear @@ vars; Evaluate[Symbol /@ vars] = m;]

For example, executing setRows["x",matrix], would create variables x1, x2, x3,... each containing the corresponding row of matrix.

To name them in any other fashion, say var1, var2,..., use setRows["var",matrix].

  • $\begingroup$ Symbol instead of ToExpression would be the perfect function here. $\endgroup$ – Julien Kluge Oct 13 '16 at 20:32
  • 1
    $\begingroup$ Thanks! I'll fix it now. I'm working on a solution that doesn't return errors if the variables already have ownvalues $\endgroup$ – dan7geo Oct 13 '16 at 20:40
  • $\begingroup$ Thanks for the answer, it's exactly what I was looking for. $\endgroup$ – EBassal Oct 13 '16 at 20:44
  • $\begingroup$ Updated to overwrite previous values of variables, if any, and to name the variables in any manner. $\endgroup$ – dan7geo Oct 13 '16 at 21:18

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.