the loop is not terminated it keeps on going

3 views (last 30 days)
Mahmoud Chawki
Mahmoud Chawki on 20 May 2023
Answered: Allen on 20 May 2023
clear variables
close all
clc
A = [1 1 2; 1 2 4; 1 2 5];
x = [1; 2; 3];
Error = 0.000001;
Diff = ones(size(x));
iterCount = 0;
while Diff>Error
x1=(A*x);
Diff=norm(abs(x1-x));
x=x1./(x1(1,1));
iterCount = iterCount + 1;
end
  1 Comment
Image Analyst
Image Analyst on 20 May 2023
You don't need us to debug your code. That takes too long. You can do it yourself once you've taken this short training:

Sign in to comment.

Answers (1)

Allen
Allen on 20 May 2023
It is not clear why you initialize Diff as a vector whos size is equal to x. After you first compute Diff using the norm function, it becomes a scalar value whos size is a single element. Also, Diff converges to 18.6918 in about six iterations and will assume a value less than what you have defined by your Error variable. Assuming you are trying to determine when the difference of Diff between iterations is less than Error, try some similar to the following. Also, it is safe practice in while loops to add an additional break, such as a max number of iterations (included below) or a total lapsed duration exceeding a defined limit.
A = [1 1 2; 1 2 4; 1 2 5];
x = [1; 2; 3];
Diff = 1;
prevDiff = 0;
Error = 1e-6;
iterCount = 0;
maxIter = 1e5;
while iterCount<maxIter && abs(Diff-prevDiff)>Error
x1 = (A*x);
prevDiff = Diff;
Diff = norm(abs(x1-x));
x = x1./(x1(1,1));
iterCount = iterCount+1;
end

Categories

Find more on Loops and Conditional Statements 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!