the loop is not terminated it keeps on going
2 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
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 Commento
Image Analyst
il 20 Mag 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:
Risposte (1)
Allen
il 20 Mag 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 Commenti
Vedere anche
Categorie
Scopri di più su Loops and Conditional Statements in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!