how to stop logical operators?

I need to create a program that calculates square root of 2 using loop. starting with t=0.5. I need to stop cycle (and print iteration number i) when the t(i) is same for approximation : if abs((t(i)-t(i+1)))<10^-6. Can anyone help me? please please please :)
t(1)=0.5
for i=1:10
t(i+1)=1/2*(t(i)+2/t(i));
if abs((t(i)-t(i+1)))<10^-6
[ i, t(i)]
else
end
end

답변 (2개)

Walter Roberson
Walter Roberson 2013년 11월 25일

0 개 추천

if condition
break
end

댓글 수: 3

kakato
kakato 2013년 11월 25일
thanks a lot, but I need without break. how to use while in this case?
t(1)=0.5;
t(2)=1/2*(t(1)+2/t(1));
i=1;
while abs((t(i)-t(i+1)))>=10^-6
t(i+2)=1/2*(t(i+1)+2/t(i+1));
i=i+1;
end
t=t(end-1);
kakato
kakato 2013년 11월 25일
Thanks a lot :)

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

Laurent
Laurent 2013년 11월 25일
편집: Laurent 2013년 11월 25일

0 개 추천

Instead of a for-loop, you can use a while loop. Something like this:
while abs((t(i)-t(i-1)))>10^-6
your calculations
i=i+1;
end

카테고리

도움말 센터File Exchange에서 Graphics Object Programming에 대해 자세히 알아보기

질문:

2013년 11월 25일

댓글:

2013년 11월 25일

Community Treasure Hunt

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

Start Hunting!

Translated by