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

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

댓글을 달려면 로그인하십시오.

답변 (1개)

Jan
Jan 2014년 2월 28일
편집: Jan 2014년 2월 28일
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.

카테고리

도움말 센터File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

질문:

2014년 2월 28일

편집:

Jan
2014년 2월 28일

Community Treasure Hunt

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

Start Hunting!

Translated by