What are different methods to avoid an infinite for/while loop?
1 view (last 30 days)
Show older comments
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 Comment
Answers (1)
Jan
on 28 Feb 2014
Edited: Jan
on 28 Feb 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.
0 Comments
See Also
Categories
Find more on Creating and Concatenating Matrices in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!