Non working while loop

조회 수: 25 (최근 30일)
Mikael Freyhult
Mikael Freyhult 2022년 5월 19일
댓글: Mikael Freyhult 2022년 5월 20일
When running the code below it seems the while loop is run through once and then executes the commands after the last end statement and ends the program.
I do not understand while the loop doesn’t actually loop until the while loop statement isn't true.
Thank you in advance
function P=fixpointiteration(val)
switch nargin
case 0
disp('0 Chosen input')
x0 = rand;
case 1
disp('1 Chosen input')
x0 = val;
otherwise
error('Unexpected input')
end
disp(x0)
f = @(x0) cos(x0);
i=0;
t = 0.00001;
x1=1;
while abs (x1-x0)>t
i=i+1
x1 = f(x0)
fprintf('x%d = %.8f\n',i,x1)
x0 = x1
end
disp('Number of iterations: ')
disp(i)

답변 (1개)

Voss
Voss 2022년 5월 19일
편집: Voss 2022년 5월 19일
The last line inside the while loop:
x0 = x1
sets x0 to x1. Therefore, when the while condition is checked again (which happens immediately), x1 and x0 are equal, so abs(x1-x0) is 0, which is not greater than t, so the loop stops iterating.
  댓글 수: 1
Mikael Freyhult
Mikael Freyhult 2022년 5월 20일
I moved the x0 = x1 expression to above the x1 = f(x0) expression and now it works.
Thank you!

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Programming에 대해 자세히 알아보기

제품


릴리스

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by