6.2: if Statement
- Page ID
Now suppose that when we find a Pythagorean triple we want to display a message. The
if statement allows you to check for certain conditions and execute statements if the conditions are met. For example:
if a^2 + b^2 == c^2 disp("Yes, that is a Pythagorean triple.") end
The syntax is similar to a
for loop. The first line specifies the condition we’re interested in. If the condition is true, MATLAB executes the body of the statement, which is the indented sequence of statements between the
if and the
MATLAB doesn’t require you to indent the body of an
if statement, but it makes your code more readable, so you should do it.
If the condition is not satisfied, the statements in the body are not .
Sometimes there are alternative statements to execute when the condition is false. In that case, you can extend the
if statement with an
The complete version of the previous example might look like this:
if a^2 + b^2 == c^2 disp("Yes, that is a Pythagorean triple.") else disp("No, that is not a Pythagorean triple.") end
for that contain other statements are called compound statements. All compound statements finish with