Mathematica Dynamic List Manipulation

I'm stuck on what I think should be a relatively simple concept. I don’t understand how Dynamic [] works with incremental list manipulation. 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? Now I want z to be dynamically updated when x changes. 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 the list a, I see a corresponding change in b and c; however, I would expect each statement to be a Part first element. Manipulations in dynamic lists are not accepted.

My question is: why do we see this behavior and how can I apply sequential manipulations with a dynamic list?

Thanks in advance.

+6
source share
2 answers

Dynamic work in an unusual way. See: Why does this not work? Dynamic selectable

The purpose of b = Dynamic[First[a]] not evaluated by anything other than the literal expression Dynamic[First[a]] , until this expression is explicitly displayed on the screen.

Therefore, when you write First[b] , you request the first part of Dynamic[First[a]] , which is First[a] .

The fact that Dynamic to some extent a tricker to show than internal functionality should not be ignored easily. A mistake in the Dynamic function will lead to a lot of confusion and frustration. However, 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]] 
+5
source

You have already received the answer why Dynamic does not work as you expected, but I will add how to achieve what (I think) you need:

 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 *) 

Using SetDelayed ( := ), you make sure that every time b and c are evaluated, the current value of a , not the value that it had at the definition point, And Dynamic ensures that the displayed value will be re-evaluated when a changes.

+2
source

Source: https://habr.com/ru/post/913225/


All Articles