What are different methods to avoid an infinite for/while loop?

When entering the code below, I keep receiving an infinite loop. How do I avoid the infinite loop?
clear
mat1 = randi(100, 200, 300);
[m, n] = size(mat1);
tic
for i=1:m
mat2(i,:) = mat1(i, :);
for j =1:n
if j==3
mat2(i, j) = 70;
elseif j==5
mat2(i,j) = 60;
elseif j==8
mat2(i,j) = 100;
elseif j==30
mat2(i, j) = 0;
else
mat2(i,j) = 5;
end
end
end
toc

1 comentario

EDITED, code formatted. Please apply a proper code formatting. Thanks.

Iniciar sesión para comentar.

Respuestas (1)

Jan
Jan el 28 de Feb. de 2014
Editada: Jan el 28 de Feb. de 2014
No, it is impossible to get an infinite FOR loop in Matlab.
I guess you observe a slow speed only. This might be caused by the midding pre-allocation of the created matrix mat2. But when I run your posted code, my old Core2Duo needs 0.033 seconds only. I would not call this "infinite". Nevertheless, ths code can be simplified drastically:
clear
mat1 = randi(100, 200, 300);
mat2 = repmat(5, size(mat1));
mat2(:, 3) = 70;
mat2(:, 5) = 60;
mat2(:, 8) = 100;
mat2(:, 30) = 0;
toc
And now it is obvious, that mat1 can be omitted completely. Strange. Did you simplify your code before posting? If so, this has been to much simplification. Use the chance to editi the text of the question and append a more detailed example code.

Categorías

Más información sobre Loops and Conditional Statements en Centro de ayuda y File Exchange.

Preguntada:

el 28 de Feb. de 2014

Editada:

Jan
el 28 de Feb. de 2014

Community Treasure Hunt

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

Start Hunting!

Translated by