Engineering Fundamentals: An Introduction to Engineering, 4th ed.c

(Steven Felgate) #1

476 Chapter 15 MATLAB


The ifStatement The ifstatement is the simplest form of a conditional control. Using the if
statement, you can execute a line or a block of your program as long as the expression follow-
ing the ifstatement is true. The syntax for the ifstatement is

if expression
a line or a block of your computer code
end

For example, suppose we have a set of scores for an exam: 85, 92, 50, 77, 80, 59, 65, 97, 72,



  1. We are interested in writing a code that shows that scores below 60 indicate failing. The
    MATLAB code for this example then could have the following form:


scores = [85 92 50 77 80 59 65 97 72 40];
for i=l:l:10
if scores (i) <60
fprintf('\t %g \t\t\t\t\t FAILING\n', scores (i))
end
end

The if, elseStatement The elsestatement allows us to execute other line(s) of computer code(s)
if the expression following the ifstatement is not true. For example, suppose we are interested
in showing not only the scores that indicate failing but also the scores that show passing. We
can then modify our code in the following manner:
scores = [85 92 50 77 80 59 65 97 72 40];
for i=1:1:10
if scores (i) >=60
fprintf('\t %g \t\t\t\t\t PASSING\n', scores (i));
else
fprintf('\t %g \t\t\t\t\t FAILING\n', scores (i))
end
end

In the MATLAB Command Window, try the preceding examples on your own.


TABLE 15.11 MATLAB’s Relational Operators
and their Descriptions

Relational
Operator It’s Meaning

 Less than
 Less than or equal to
 Equal to
 Greater than
 Greater than or equal to
 Not equal to

Copyright 2010 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).

圀圀圀⸀夀䄀娀䐀䄀一倀刀䔀匀匀⸀䌀伀䴀圀圀圀⸀夀䄀娀䐀䄀一倀刀䔀匀匀⸀䌀伀䴀

Free download pdf