Finding the matrix I generated two iterations back, while loop

11 次查看(过去 30 天)
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

采纳的回答

Matt J
Matt J 2020-1-27
编辑:Matt J 2020-1-27
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

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Strategy & Logic 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by