0

Really simple question... I'm trying to exit a while loop early:

while optimal < 1 
    %some code...
    x=0  %This is just here to set my example...
    if x~=0
      break
    end 
end

But for some reason even though x was set to 0, the if statement always fails as it says x isnt equal to 0 and the while loops will never exit

Thanks!

user2234552
  • 55
  • 1
  • 4
  • 3
    I think you must use `x==0` rather than `x~=0` – articuno Jan 22 '15 at 05:23
  • Are you **absolutely** sure that `x = 0`? Are you doing some calculations in your loop where `x` is **expected to be** zero when it isn't? This post may be helpful: http://stackoverflow.com/questions/686439/why-is-24-0000-not-equal-to-24-0000-in-matlab – rayryeng Jan 22 '15 at 07:38

1 Answers1

2

if you want to exit if x i equal to 0 then you want to write:

if x==0

however, unless you want to exit the loop before the end, you could also add the condition on the x in the while line:

while (optimal < 1 && x~=0)

"as long as optimal is less than one and x is NOT 0"

yoh.lej
  • 1,104
  • 6
  • 14