the loop is not terminated it keeps on going

3 次查看(过去 30 天)
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 个评论
Image Analyst
Image Analyst 2023-5-20
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:

请先登录,再进行评论。

回答(1 个)

Allen
Allen 2023-5-20
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

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by