Stopping criteria matlab iteration

3.2k Views Asked by At

I want to add an While-loop to my matlab-code so that it will stop when the iteration is good enough. With some kind of tolerance, eg. 1e-6.

This is my code now. So i need to add some kind of stopping criteria, i have tried several times now but it won't work... I appreciate all of ur help!

x(1)=1;
iterations = 0;
tolerance = 1e-6;

% Here should the while be....

for i=1:N     
    x(i+1)=x(i);        
    for j=1:N              
        x(i+1)=F(x(i),x(i+1)); 
    end
end
iter= iter + 1;
1

There are 1 best solutions below

2
On

Well, somehow you need to compute the 'error' you are doing in each iteration. In your case it would be something like this:

iter = 0;
tolerance = 1e-6;
error=1;
x=F(x);

while(error>tolerance)    
    x2=x;        
    x=F(x);
    error = x-x2;
    iter= iter + 1; 
end

Note how at the beginning the error is set to 1 so we make sure it goes inside the loop. We also compute the first instance of x outside the loop. F(x) will be your function to evaluate, change it for whatever you need.

Inside the loop assign the old value of x to x2, then compute the new x and finally compute the error. Here I compute the error as x-x2 but you might need to compute this error in another way.

The loop will exit whenever the error is lower than the tolerance.