3
$\begingroup$

This question already has an answer here:

If I let j=2, then

Table[i, {i, 10}][[j]] returns 2.

But I want the j to be Dynamic,

so I use Table[i,{i,10}][[Dynamic@j]],

but it shows an error:

Part::pkspec1: The expression 2 cannot be used as a part specification.

How can I get the dynamic index of a Table?

Thanks.

$\endgroup$

marked as duplicate by C. E., Öskå, happy fish, MarcoB, Kuba Feb 20 '17 at 20:45

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • $\begingroup$ You need to put Dynamic outside the expression. Please see Where should Dynamic be placed in an expression?. $\endgroup$ – C. E. Feb 20 '17 at 5:51
  • $\begingroup$ Thanks @C.E. Your comment solved my problem. $\endgroup$ – cmal Feb 20 '17 at 6:31
  • $\begingroup$ In addition to linked topics you can take a look at: 85491 $\endgroup$ – Kuba Feb 20 '17 at 20:47
8
$\begingroup$

Think of Dynamic as just spot on the screen. That is all.

This spot will get updated automatically, when any variable contained in the expression that generated this spot initially has changed its value elsewhere in the notebook. (currently visible part of the notebook)

To make a spot dynamic, wrap the expression which generated the result with Dynamic. In your example, it will become

idx = 1;
data = Table[i^2, {i, 10}];
Dynamic[data[[idx]]]
<-----  This spot now is dynamic. It will update anytime data or idx change

enter image description here

Notice that when idx changes, the spot changes. Because idx was inside the expression which generated that spot initially.

If the data itself changes, also the spot will get updated automatically.

enter image description here

The front end, spends all its time monitoring variables that change in the notebook, and checking if any visible dynamic spot on the screen needs to get updated (by re-evaluating the whole expression which generated that spot). What a boring life the Font end has :) but it does it very quickly.

Also notice, that Dynamic really makes sense to use to only wrap expression which generates output on the screen. Since it is the spot itself which is Dynamic. This means the kernel does not know about Dynamics and it is all handled by front end. At least as far as I know.

$\endgroup$

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