フィルターのクリア

the loop is not terminated it keeps on going

1 回表示 (過去 30 日間)
Mahmoud Chawki
Mahmoud Chawki 2023 年 5 月 20 日
回答済み: Allen 2023 年 5 月 20 日
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 Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by