# How to increase maximum number of iterations in a 'for' loop, when in the loop?

2 views (last 30 days)
Kaushal Sorte on 20 Nov 2020
Commented: Steven Lord on 20 Nov 2020
A = [9 1 2 3; 1 7 2 3; 1 5 10 2; 1 2 3 9]
B = [1;2;3;4]
n = size(B,1);
Tolerance = 10^-15;
x = zeros([n,1]); %Initialization vector defaultly set as zero for ease of operation.
Norm_Values = []; % Storing first norm values.
K = 10;
for k = 1:K
T = x; % Storing previous x vector
for i = 1:n
x(i) = (B(i) - A(i,[1:i-1 i+1:n])*x([1:i-1 i+1:n]))/A(i,i);
end
if (norm((x-T),1) < Tolerance) % Checking for convergence.
fprintf('GaussSeidel has converged in %d iterations.\n',k)
break
elseif (k == K)
K = K + 10 %Extending for loop
end
end
If the norm does not go below tolerance within K iterations, I want to increase the number of iterations. But it is not working. It is only going up to 10 iterations.
(Above is just parts of the whole code.)
I don't want to use 'while' here because I would then have to do the 1st iteration outside the loop.
Help will be appreiciated.
Thanks in anticipation.

Alan Stevens on 20 Nov 2020
while (norm((x-T),1) > Tolerance)
...etc
end

Kaushal Sorte on 20 Nov 2020
Ohhh. That is a good fix Alan. Thanks. I would that.
But, is it possible at all to change for loop max iteration limit while running?
Rik on 20 Nov 2020
It might be possible, but you should not do that. If you don't know the iterator values in advance, you should use a while loop.
You can also use the higher number of iterations and use break inside an if statement, but that will not work for your setup.
Steven Lord on 20 Nov 2020
No. As soon as you enter the for loop, MATLAB calculates the values of the loop variable over which it iterates. You can (but shouldn't) change the loop variable inside the body, but any such changes will be overwritten with the next iterate at the start of the next execution of the body of the loop.

VBBV on 20 Nov 2020
Delete the break statement inside the if condition and run again.

#### 1 Comment

Kaushal Sorte on 20 Nov 2020
Well, if I do that, it would not stop on converging.

R2020b

### Community Treasure Hunt

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

Start Hunting!