images

5.1   Conditional execution: The if statement

5.2   Logical expressions

5.3   Logical variables

5.4   for loops

5.5   while loops

5.6   Other control flow commands

The simplest programs consist of a series of commands that are executed in order, one after the other. Because MATLAB has some very powerful commands, such a program can be quite useful. The real power of programming becomes apparent, though, when we can structure a program so that (a) which commands are executed depends on the values currently stored in variables, and (b) some commands can be executed repeatedly. Statements that don’t directly execute an action, but rather control which other commands will be executed, are called “control flow commands.” In MATLAB the if statement allows conditional execution, and repetitive execution, making “loops,” is accomplished using the for or while statements.

After mastering the material in this chapter you should be able to write programs that:

  • Use an if statement to conditionally execute a block of commands.
  • Express complex logical conditions using a combination of logic operators.
  • Create logical variables that function as program flags or switches.
  • Repeatedly execute a command block a set number of times using a for loop.
  • Repeatedly execute a command block until a logical condition is met using a while loop.
  • Use a switch-case statement to conditionally execute one of several ...

Get Learning to Program with MATLAB: Building GUI Tools now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.