The “if” Statement

 (Chp. 6.3 Pgs. 255-264)

 

·       The relational and logical operators allow you to test relationships between variables.  What you probably want to do is perform different things depending on the output of the relational and logical operators.  That’s where the “if” statement comes into play.

 

·       Here is the structure of an if statement in MATLAB:

 

if  <put some relational/logical condition here>

          All the operations you want to do when condition above is true

end

 

 

·       Here is an example.  Put this in an m-file called recip.m and execute it.

 

x=input('enter a number to take the reciprocal of: ');

 

if x==0

          disp('the reciprocal is infinity! ')

end

 

if x~=0

          disp('the reciprocal is: ')

          y=1/x

end

 

·       A more efficient way to do what we did above uses the else statement.  Here is the structure:

 

if  <put some relational/logical condition here>

          All the operations you want to do when condition above is true

else

          All the operations you want to do when condition is not true

end

 

·       Thus, our code would read:

 

x=input('enter a number to take the reciprocal of: ');

 

if x==0

          disp('the reciprocal is infinity! ')

else

          disp('the reciprocal is: ')

          y=1/x

end

 

·       Here is a flowchart of the program above using the if-else-end structure.

 

·       You can put if statements inside if statements.

 

·       You can put if statements inside of for loops.  We will see that shortly in our rocket example!