I am stuck on what I think should be a relatively simple concept. I am not understanding how Dynamic[] functions with regarding incremental list manipulations. Consider the following statements:
In[459]:= x={{1,2}};
In[462]:= y=First[x]
Out[462]= {1,2}
In[463]:= z=First[y]
Out[463]= 1
Simple right? Now, I want z to dynamically update when I change x. Here is my attempt:
In[458]:= a={{1,2}};
In[452]:= b=Dynamic[First[a]]
Out[452]= {1,2}
In[449]:= c=Dynamic[First[b]]
Out[449]= {1,2}
As I change the values in list a, I see corresponding change is b and c; however, I would expect each statement to Part the first element. Manipulations on Dynamic lists are not taking.
My question is why do we see this behavior, and how can I apply consecutive Dynamic list manipulations?
Thank you in advance.
Dynamic works in an unusual way. See: Why won't this work? Dynamic in a Select
The assignment b = Dynamic[First[a]]
does not evaluate to anything other than the literal expression Dynamic[First[a]]
until that expression is to be visibly displayed on screen.
Therefore when you write First[b]
you are asking for the first part of Dynamic[First[a]]
which is First[a]
.
The fact that Dynamic
is in a way more of a display trick than an internal functionality should not be overlooked lightly. Mistaking the function of Dynamic
will lead to much confusion and frustration. Nevertheless, in your simple example you can get the behavior you want, at least visually, with this:
b = Dynamic[First[a]]
c = Dynamic[First@First[b]]
You've already gotten an answer why Dynamic
doesn't work as you expected, but I'll add how to achieve what (I think) you want:
a={{1,2}}
(*
==> {{1,2}}
*)
b:=First[a];Dynamic[b]
(*
==> {1,2}
*)
c:=First[b];Dynamic[c]
(*
==> 1
*)
a={{3,4}}
(*
==> {{3,4}}
-- The displays for b and c now change to {3,4} and 3
*)
By using SetDelayed
(:=
) you make sure that every time b
and c
are evaluated, the current value of a
is used, rather than the value it had at the point of definition. And the Dynamic
makes sure that the displayed value is re-evaluated whenever a
is changed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With