2
$\begingroup$

When I do a simple operation like this

fib = Table[Fibonacci[i], {i, 15}]

and then look to find the position of a certain value, everything works fine:

indices = Flatten@Position[fib, _?(# > 99 &)]
{12, 13, 14, 15}

However, once I make the table Dynamic and try the same thing the position function does not seem to work:

Slider[Dynamic@n, {1, 10000, 1}, Appearance -> "Labeled"]
fib = Dynamic@Table[Fibonacci[i], {i, n}];
indices = Flatten@Position[fib, _?(# > 99 &)]
{}

Upon further investigation the reason seems to be that Dynamic turns the Table into a nested list (that isn't actually nested, i.e. it still appears as {"List"} and not {{List}}).

For example, without Dynamic fib[[1]] returns the first element and fib[[2]] returns the second. However, with Dynamic, fib[[1]] returns the entire list and fib[[2]] returns an error that

Part 2 of {1,1,2,3,5,8,13,21,34,55,89,144,233,377,610} does not exist.

What is going on here and how do I find the position of elements in a Dynamic Table?

$\endgroup$
  • 1
    $\begingroup$ It has become Dynamic[List[...]]. Not sure what is your goal but you can: Dynamic[ fib = ... ; indices = ...] and later you can use those variables $\endgroup$ – Kuba Nov 19 '15 at 12:40
2
$\begingroup$

You are setting fib to a Dynamic object. Thus its Head becomes Dynamic instead of List. Use FullForm to see the full structure.

FullForm[fib]

Dynamic[Table[Fibonacci[i], List[i, n]]]

Length@fib

1

One can get the current value of the dynamic object fib using Setting and avoid making indices another Dynamic object by putting its assignment inside Dynamic.

Slider[Dynamic@n, {1, 100, 1}, Appearance -> "Labeled"]
fib = Dynamic@Table[Fibonacci[i], {i, n}];
Dynamic[indices = Flatten@Position[Setting@fib, _?(# > 99 &)]]

enter image description here

$\endgroup$
  • $\begingroup$ Why does this work? $\endgroup$ – andrewmh20 Nov 19 '15 at 13:31
  • 1
    $\begingroup$ @andrewmh20 keep in mind indices is not a list here too. $\endgroup$ – Kuba Nov 19 '15 at 13:40
  • $\begingroup$ I edited my answer to make indices a List. $\endgroup$ – Karsten 7. May 26 '16 at 8:28

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