Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

I would like to make a Table whose iterator has a dynamically updated endpoint, i.e.

Table[i,{i,1,Dynamic[n]}]

Is this possible? Here is the context:

n=1
SetterBar[Dynamic@n, Range[1, 10, 1]]
f[x_]:=Module[{y},
        y=Table[0,{i,1,Dynamic[n]+4}]
        For[i=3,i<=Dynamic[n]+4,i++,
             y[[i]]=y[[i-1]]+2y[[i-2]]
          ]
       ]
y=f[Dynamic[x]]

I get the error

Iterator {i,1,4+1} does not have appropriate bounds.

As another example of how I'd like to use this, here is fully functional code:

n=1;
Manipulate[Table[ToExpression["x" <> ToString@i], {i, 1,Dynamic@n + 1}], {x1, 1, 10}, {x2, 1, 10}]
share|improve this question
3  
You need to think about where you place Dynamic. In this simple example you should place it outside of Table. If you wrap Table in something else, Dynamic might have to be moved even further away from Table. The idea is to make the expression dynamic, not just one variable. Without knowing what you are planning on using this for any answers that we can provide might not help you that much. –  Pickett Aug 24 at 18:34

2 Answers 2

up vote 3 down vote accepted

As mentioned in the comment by Pickett, you have to wrap Dynamic around the expression that is to be displayed. You also forgot to return a value from your function f. Here is a modification of your code that works:

Clear[f]

f[x_] := Module[{y},
  y = Table[0, {i, 1, n + 4}]; 
  For[i = 3, i <= n + 4, i++, y[[i]] = y[[i - 1]] + 2 y[[i - 2]]];
  y]

n = 1;
SetterBar[Dynamic@n, Range[1, 10, 1]]

bar

Dynamic[f[x]]

$\{0,0,0,0,0,0,0,0,0,0\}$

share|improve this answer
    
Thanks so much! I guess I was writing the Dynamics inside-out, or so to say - I also fixed the extra line I added to the question, thanks to you: Manipulate[ Dynamic[Table[ ToExpression["x" <> ToString@i], {i, 1,n + 1}]], {x1, 1, 10}, {x2, 1, 10}] –  David Aug 24 at 18:55

Applying Mathematica's functional programming tools to your problem makes the definition of your function f a one-liner. Note that I give the function argument x a real semantic role in f.

n = 1;
f[x_] := Nest[Append[#, #[[-1]] + 2 #[[-2]]]&, {x, x}, n + 2]
SetterBar[Dynamic @ n, Range[10]]

setter-3

Dynamic @ f[1]
{1, 1, 3, 5, 11, 21, 43}

If you were to change the setter bar setting from 3 as shown to 10, the output from f[1] would change to

{1, 1, 3, 5, 11, 21, 43, 85, 171, 341, 683, 1365, 2731, 5461}
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.