Chapter 3: MATLAB Basics: Control Flow and Conditional Statements
In MATLAB, control flow and conditional statements enable you to control the execution path of a program based on different conditions. This tutorial discusses common control flow constructs in MATLAB in detail, and provides concrete examples and code examples.
1. If-else statement
An if-else statement is a common type of conditional statement that allows you to choose a different path of execution based on a given condition. Following is the sample code using if-else statement.
x = 10;
if x > 5
disp("x大于5"); % 条件为真时执行的代码块
else
disp("x小于等于5"); % 条件为假时执行的代码块
end
result:
x大于5
The code above first checks if x is greater than 5. disp("x大于5")
If the condition is true, this line of code will be executed ; otherwise, disp("x小于等于5")
this line of code will be executed.
By using the if-elseif-else structure, you can choose between multiple conditions.
x = 12;
if x < 10
disp("x小于10");
elseif x < 20
disp("x小于20,大于等于10");
else
disp("x大于等于20");
end
result:
x小于20,大于等于10
In this example, if x is less than 10, disp("x小于10")
this line of code will be executed; if x is greater than or equal to 10 but less than 20, disp("x小于20,大于等于10")
this line of code will be executed; otherwise, disp("x大于等于20")
this line of code will be executed.
2. For Loop
For loops allow you to execute a piece of code repeatedly, typically for traversing an array or for a specified number of iterations. Following is the sample code using for loop.
for i = 1:5
disp(i);
end
result:
1
2
3
4
5
The above code will print out the numbers from 1 to 5. In each iteration, the variable i will take the value of 1, 2, 3, 4 and 5 and the code block inside the loop will be executed.
You can also control the number of iterations of the loop by specifying a step size.
for i = 1:2:9
disp(i);
end
result:
1
3
5
7
9
In this example, the loop iterates over numbers 1, 3, 5, 7, and 9 with a step size of 2.
3. While loop
While loops are used to repeatedly execute a piece of code while a certain condition is met. This condition is checked before each iteration. Following is the sample code using while loop.
x = 5;
while x > 0
disp(x);
x = x - 1;
end
result:
5
4
3
2
1
The above code will start at 5, print the value of x and subtract 1 from x each iteration. The loop will terminate when x equals 0.
4. Break and Continue statements
Use the break statement to terminate the loop early without waiting until the condition is met. Use the continue statement to skip the remaining code of the current loop and transfer control to the next iteration. Following is sample code for both statements.
for i = 1:10
if i == 7
break; % 提前终止循环
elseif i == 3
continue; % 跳过当前迭代
end
disp(i);
end
result:
1
2
4
5
6
In the above example, when i is equal to 7, the break statement causes the loop to be terminated immediately. When i is equal to 3, the continue statement skips the remaining code of the current iteration and goes directly to the next iteration.