Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Mathematica -> making multiple variables in one go?

  1. Sep 12, 2011 #1
    [ANSWERED] Mathematica -> making multiple variables in one go?

    Ok so lets say i know how many variables i want:

    numberofvariables = 5;

    and then i want to create 5 different variables, say X1, X2, X3, X4, X5 based on some formula, say:

    Xi = 5+i^2

    but i want this creation of variables to be done automatically, without me having to explicity type out and declare X1, X2, X3,...separately...

    is this possible?

    I really need to know, because say i want numberofvariables = 200, it would be a pain to have to separately declare X1 through X200...

    thank you so much.

    (Note: this is a radically simplified version of what i am doing...there is not need to substitute a different method to solve the above problem, i just need dynamic variable declaration?)
    Last edited: Sep 12, 2011
  2. jcsd
  3. Sep 12, 2011 #2


    User Avatar
    Staff Emeritus
    Science Advisor
    Gold Member

    Are you really, really, really sure that you can't use variables such as x[1], x[2], x[3], ...?
  4. Sep 12, 2011 #3
    Oh i was able to create a For loop and assign X variables like that....works

    thank you very much Hurkyl
  5. Sep 12, 2011 #4
    You can also construct the Xi symbols programmatically:

    Do[Evaluate[Symbol["x" <> ToString]] = 5 + i^2, {i, 5}]
  6. Oct 18, 2011 #5
    I sort of have a similar issue.

    So if I was to do some nonlinear fit of N objects (x1 through xN) with parameters A for each, A1, A2, A3 ... AN, but the number of objects is dependent on what data I'm looking at. Is there some way to generate those parameters/object labels depending on the number of objects I have?

    So if I write:
    NonlinearFit[data, formula, {A1, A2, ... AN}, {x1, x2... xN}]

    I can create the formula by joining strings together and then converting to an expression, the problem I have is somehow including the A1...AN parameters and x1... xN variables given some N.

    Thanks for any advice, this has been bugging me the past year.
  7. Oct 18, 2011 #6
    Create the parameters and variables almost the same way you create the formula.

    (* now look at the result *)

    From In[1]:={A1,A2,A3,A4,A5,A6,A7,A8,A9,A10,A11,A12}{x1,x2,x3,x4,x5,x6,x7,x8,x9,x10,x11,x12}

    Then you can write

    NonlinearFit[data, formula, params, vars]

    Just make certain you have not previously assigned values to any Ai or xi.
    If you have assigned values to any of those you may want to look at Clear[].
  8. Oct 20, 2011 #7
    Thanks! That's exactly what I needed.
Share this great discussion with others via Reddit, Google+, Twitter, or Facebook