Make an while-loop stop when conditions is fullfilled

2 ビュー (過去 30 日間)
Helene Andersen
Helene Andersen 2016 年 5 月 12 日
編集済み: Weird Rando 2016 年 5 月 12 日
First of all I am new to MATlab, but I have made this code for Newton's method. My problem is that I have said that the code should make 100 iteration, but I want it to stop when it converges. How can I do this?

回答 (2 件)

Walter Roberson
Walter Roberson 2016 年 5 月 12 日
if convergence_test_goes_here
break;
end
for example,
if abs(fx - prev_fx) < 1E-10
break
end

Weird Rando
Weird Rando 2016 年 5 月 12 日
編集済み: Weird Rando 2016 年 5 月 12 日
Just use an AND logic '&' to identify both condition for the while loop.
clc
clear
%%Website
%f(x) = x^3 - x + 1 = 0
%f'(x) = 3x^2 - 1
% The root of the function is between -1 and -2
x = -2:0.1:2;
y = x.^3 - x + 1;
plot(x,y)
grid on
%%Example
counter = 0;
converge = -1.3247;
x1 = -1; %initial guess
while counter < 100 & round(x1*10000)/10000 ~= converge
x1 = x1 - (x1^3 - x1 + 1)/(3*x1^2 - 1)
counter = counter + 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