why is this function running infinitely?
Mostrar comentarios más antiguos
I am trying to create an eye matrix that spreads until all the inside numbers inside the border of zeros are ones, I did this using loops and it works it just never stops even after the sum of the entire matrix equals 400
Master1 = eye(22,22);
Master1(1, :) = zeros(1, 22);
Master1(22, :) = zeros(1, 22);
scan=[3:3]
temp=Master1
i=0;
while sum(sum(Master1))<400
for r=2:21
for c=2:21
scan=((r-1):(r+1):(c-1):(c+1))
if sum(scan)<1
temp(r,c)=1
else sum(scan)>1
temp(r,c)=1
end
end
end
end
Master1=temp
i=i+1
1 comentario
Jan
el 29 de Nov. de 2021
A simplification of:
Master1(1, :) = zeros(1, 22);
Master1(22, :) = zeros(1, 22);
scan=[3:3]
is
Master1(1, :) = 0;
Master1(22, :) = 0;
scan = 3;
Respuesta aceptada
Más respuestas (1)
% Simplified version:
Master1 = eye(22,22);
Master1(1, 1) = 0;
Master1(22, 22) = 0;
scan = 3;
temp = Master1;
i = 0;
while sum(Master1(:)) < 400
for r = 2:21
for c = 2:21
scan = ((r-1):(r+1):(c-1):(c+1)); % ???
if sum(scan) ~= 1
temp(r,c)=1
end
end
end
end
Master1 = temp;
i = i+1;
This will most likely not do, what you expect:
(r-1):(r+1):(c-1):(c+1)
The colon operator is defined with two : only: a:b:c is the vector from a to c in steps of b. This replies a vector. In the next step this vector is used as 1st input for the next colon operator:
((r-1):(r+1):(c-1)) : (c+1)
% ^ evaluated at first ^ then this follows
If a vector is used as input of the colon operator, only the first element is considered and the rest is ignored. Therefore your code is equivalent to:
% (r-1):(r+1):(c-1):(c+1)
(r-1):(c+1)
What is the purpose of the variable scan? Do you want to collect indices or the values of the matrix?
The problem causing the infinite loop, is that the body of the loop does not change the condition. If sum(Master1(:)) < 400 is true initially, this will never change, because Master1 is not modified inside the loop.
Why do you use the copy temp of Master1 and not the data directly? Maybe you want:
M = eye(22,22);
M(1, 1) = 0;
M(22, 22) = 0;
i = 0;
while sum(M(:)) < 400
for r = 2:21
for c = 2:21
scan = M((r-1):(r+1), (c-1):(c+1));
if sum(scan(:)) ~= 1
M(r,c) = 1;
end
end
end
M
i = i+1;
end
i
Categorías
Más información sobre Loops and Conditional Statements en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!