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
Jan
2014년 2월 28일
EDITED, code formatted. Please apply a proper code formatting. Thanks.
답변 (1개)
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에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!