while loop with a boolean expression
    8 Ansichten (letzte 30 Tage)
  
       Ältere Kommentare anzeigen
    
    mazari ahmed
 am 20 Mär. 2015
  
    
    
    
    
    Beantwortet: mazari ahmed
 am 9 Apr. 2015
            why my boolean expression is not working , is there any syntax error. here is my code :
v=false;
while ((i < N)&&(v==false)) if (condition) v=true; i=i+1; else i=i+1; end end
0 Kommentare
Akzeptierte Antwort
  Image Analyst
      
      
 am 20 Mär. 2015
        Don't even use v. Just break:
while (i < N) 
    if (condition) 
       break;
    end 
    i=i+1;
end
0 Kommentare
Weitere Antworten (2)
  Stephen23
      
      
 am 20 Mär. 2015
        
      Bearbeitet: Stephen23
      
      
 am 20 Mär. 2015
  
      A few tips:
- v==false is rather awkward code, as the while operation requires a logical value: v is already a logical value, so instead of doing this round-about numeric comparison, why not just use the simplest form of ~v instead?
- Do not use i or j as loop variables names, as these are the names of the inbuilt imaginary unit.
- Using the else statement and repeating the code that increments the loop variable could be replaced by simply incrementing the variable once after the if statement.
- the if statement does nothing useful: why not just define v directly using condition?
Altogether we get this:
v = false;
while k<N && ~v
    v = ~condition;
    k = k+1;
end
which we can then simplify be noting that everywhere ~v is used can simply be condition instead:
condition = true;
while k<N && condition
    k = k+1;
end
0 Kommentare
Siehe auch
Kategorien
				Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange
			
	Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!


