Finding the matrix I generated two iterations back, while loop

8 views (last 30 days)
I need my code to remember the matrix it generated two iterations back, and if this matrix is equal to the present one I want the code to break out of my while loop. This is a variation of the 'game of life' and the functions are written in swedish.
%%
C = [0 0 0; 1 1 1;0 0 0];
B = [zeros(1, N); C; zeros(1, N)];
A = [zeros(N+2, 1) B zeros(N+2, 1)];
D=zeros(N+2);
same=0;
k=0;
while same==0;
k=k+1;
for i=2:N+1;
for j=2:N+1;
D(i,j)=antalgrannarv2(A,i,j);
end
end
for i=1:N+2;
for j=1:N+2;
D(i,j)=celldestiny(D,i,j);
end
end
if A==D;
same=1;
else
same=0;
end
%here I would like the program to remember the second last matrix it generated and if
%the present one is equal, break out of the loop.
A=D;
find(0)
clf
plotroutine(A)
pause(0.2)
end

Accepted Answer

Matt J
Matt J on 27 Jan 2020
Edited: Matt J on 27 Jan 2020
One option is to maintain a list of the last two D's in a cell array:
C = [0 0 0; 1 1 1;0 0 0];
B = [zeros(1, N); C; zeros(1, N)];
A = [zeros(N+2, 1) B zeros(N+2, 1)];
D=zeros(N+2);
Dprevious={A,D}; %<----------------added
same=0;
k=0;
while same==0;
k=k+1;
for i=2:N+1;
for j=2:N+1;
D(i,j)=antalgrannarv2(A,i,j);
end
end
for i=1:N+2;
for j=1:N+2;
D(i,j)=celldestiny(D,i,j);
end
end
if isequal(D, Dprevious{1}); %<------------changed
same=1;
else
same=0;
Dprevious={Dprevious{2}, D}; %<-------- added
end
A=D;
end

More Answers (0)

Categories

Find more on Strategy & Logic in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!