the loop is not terminated it keeps on going
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
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 Kommentar
Image Analyst
am 20 Mai 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:
Antworten (1)
Allen
am 20 Mai 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
0 Kommentare
Siehe auch
Kategorien
Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!