My goal is to make a dynamic simulation. For that, I create a list of 2D matrices. Each matrix is supposed to change an entry at a time (a "time" instant is each step of the list, which is iterable).
I use this format because I want to use this list of matrices (that I create with Python) in Mathematica, to visualize the dynamics using the "Manipulate" function.
n=3
M=[[0,0,0][0,1,0][0,0,0]] # initial matrix M (a simple example)
l=[M]
numbersteps=10
for step in range(1,numbersteps+1):
for v1 in range(1,n**2+1):
for v2 in range(1,n**2+1):
i=VertexIndex (M,v1)[0] # i,j, ki, kj are indexes,
j=VertexIndex (M,v1)[1] # which I calculate in the function VertexIndex
ki=VertexIndex (M,v2)[0] # VertexIndex returns (int1,int2)
kj=VertexIndex (M,v2)[1]
if M[i-1][j-1]==1:
M[i-1][j-1]=-1
M[ki-1][kj-1]=1 # changes the entry M(ki, kj)
l.append(M) # list of each matrix M, for each step
I was expecting to get
l=[M(step1),M(step2),M(step3),...]`
Because M is changing its entries, I would see the dynamics when I run the sequence of different M's. But what I got was simply a list of the final matrix M, "numbersteps" times, i.e.,
l=[M(finalstep),M(finalstep),M(finalstep),...], such that len(l)=numbersteps.
Does this make sense? Where is my mistake? I appreciate any help.
The object M
is created only once during its initialization, so each time you append M
to l
with l.append(M)
, you're appending a reference to the same object for each iteration, so as the object mutates, the values of all references to this object change as well.
You can instead append a deep copy of the list of lists (add from copy import deepcopy
first):
l.append(deepcopy(M))