Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mathematica Dynamic List Manipulation

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.

like image 805
slouis Avatar asked Apr 15 '12 05:04

slouis


2 Answers

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]]
like image 164
Mr.Wizard Avatar answered Oct 09 '22 16:10

Mr.Wizard


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.

like image 37
celtschk Avatar answered Oct 09 '22 16:10

celtschk