Automatically create array of named variables

  • Context: Mathematica 
  • Thread starter Thread starter Swamp Thing
  • Start date Start date
  • Tags Tags
    Array Variables
Join the discussion
Ask a follow-up here, or get your own question answered by working scientists, mathematicians and engineers — people, not an autocomplete.
Real named experts · corrections over time · the nuance an AI answer skips
5 replies · 2K views
Swamp Thing
Insights Author
Messages
1,062
Reaction score
819
In the following example...
Code:
Manipulate[
             ListPlot[{p1, p2}, PlotRange -> {{0, 3}, {0, 3}}, Joined -> True],
             {{p1, {0.5, 0.5}}, Locator},
            {{p2, {1, 0.7}},   Locator}
         ]

... we have created variables p1 and p2 that are local to the Manipulate block, and we use them to set up two locators on the ListPlot. Now if we want to create a large number of locators, we could manually type in a large number of p1, p2, p3, p4 ... and so on. But is there a way to build these arrays of named variables programmatically?

The above is just one example, but there are other constructs in Mathematica where an input to a function must contain multiple named variables. It would be nice to automate the creation of large lists like that.
 
on Phys.org
A bit of googling turned up the concept of indexed variables. For example, we can do :
P = Table[Indexed[p, i], {i, 1, 7}]

which gives us ##P = \{ p_1, p_2, p_3, p_4, p_5, p_6, p_7 \}## , and we can use these as our seven variables.

This takes us one step forwards... But unfortunately, when we look at the locator specification at the end, it doesn't have a true list like format. It's just a series of extra arguments to the Manipulate. So the question turns into, "how can we feed in multiple arguments into a function automatically, when it can accept a series of arguments?"========== Edit: I realized that the indexed variables don't work as I thought ===
 
ListPlot will iterate over a list of expressions:

Code:
P = Table[Indexed[p, i], {i, 1, 7}]
pointList = Table[{RandomReal[{0, 3}], RandomReal[{0, 3}]}, {i, 1, 7}]
Manipulate[
ListPlot[P, PlotRange -> {{0, 3}, {0, 3}},
  Joined -> True], {{P, pointList}, Locator}]
 
Reply
  • Love
Likes   Reactions: Swamp Thing
cabrera said:
ListPlot will iterate over a list of expressions:

Really neat. Thanks!

I had tried unsuccessfully to get Manipulate to accept a list of locators, but I gave up as I couldn't figure out the right syntax... and I wrongly concluded that it just isn't designed to take a bracketed list.

Even now, your code has some subtlety that I can barely wrap my head around.