MATLAB - Decisions
MATLAB - Decision Making
Section titled “MATLAB - Decision Making”Decision-making structures are a fundamental part of programming. They allow your code to respond differently to different situations, making your programs intelligent and dynamic. These structures require you to specify one or more conditions to be evaluated. Based on whether a condition is true or false, a specific block of code is executed.
Think of it like a fork in the road. A condition (e.g., “Is it raining?”) determines which path your program takes. If true, it might execute the ‘bring an umbrella’ code. If false, it might execute the ‘wear sunglasses’ code. This control over the program’s execution flow is essential for almost any task.
MATLAB provides a standard set of decision-making statements, common to many programming languages. Here is a summary of the available structures:
| No. | Statement & Description |
|---|---|
| 1 | if … end statement An if ... end statement consists of a logical expression followed by one or more statements that execute only if that expression is true. |
| 2 | if…else…end statement An if statement can be followed by an optional else block. The else block executes when the logical expression is false. |
| 3 | if…elseif…else…end statements This structure is used to decide between several (more than two) alternatives. As soon as an if or elseif expression is found to be true, the corresponding statements are executed, and the rest of the structure is skipped. |
| 4 | nested if statements You can use one if or elseif statement inside another. However, for complex logic, this can become hard to read and should be used with care. |
| 5 | switch statement A switch statement provides a clean way to test a single variable for equality against a list of possible values. |
| 6 | nested switch statements Similar to nested if statements, you can use a switch statement inside another switch statement. |
The if...end Statement
Section titled “The if...end Statement”This is the simplest form of decision making. The code block is executed only if the condition is met.
%% Example: Check if a temperature reading indicates a fevertemperature = 38.5;
if temperature > 37.5 disp('Warning: High temperature detected. Potential fever.');end
% --- Output ---% Warning: High temperature detected. Potential fever.The if...else...end Statement
Section titled “The if...else...end Statement”This structure provides an alternative path for when the condition is false.
%% Example: Check if a student passed or failedscore = 65;passingGrade = 50;
if score >= passingGrade disp('Congratulations, you passed!');else disp('You did not pass. Better luck next time.');end
% --- Output ---% Congratulations, you passed!The if...elseif...else...end Statement
Section titled “The if...elseif...else...end Statement”This is the ideal structure for checking multiple, mutually exclusive conditions. It is more readable than deeply nested if statements.
%% Example: Assign a letter grade based on a scorescore = 88;
if score >= 90 grade = 'A';elseif score >= 80 grade = 'B';elseif score >= 70 grade = 'C';elseif score >= 60 grade = 'D';else grade = 'F';end
fprintf('The grade is: %s\n', grade);
% --- Output ---% The grade is: BThe switch Statement
Section titled “The switch Statement”A switch statement is an excellent choice when you need to check a single variable against a list of specific, discrete values. It works with numbers, character vectors, and modern string or categorical arrays.
%% Example: Respond based on a selected menu option (using strings)% In modern MATLAB, using strings (double quotes) is preferred for text.menuSelection = "Save";
switch menuSelection case "Open" disp('Opening file...'); case "Save" disp('Saving file...'); case "Close" disp('Closing file...'); otherwise disp('Invalid selection.');end
% --- Output ---% Saving file...Best Practices for Decision Making
Section titled “Best Practices for Decision Making”- Use
elseiffor Clarity: Avoid deeply nestedifstatements. Anif...elseif...elsechain is much easier to read and maintain. - Leverage Short-Circuiting: MATLAB uses short-circuiting for
&&(AND) and||(OR). In an expression likeconditionA && conditionB,conditionBis only evaluated ifconditionAis true. This can be used to prevent errors, for example:if (x ~= 0) && (1/x > 5), which prevents a division-by-zero error. - Handle the ‘Otherwise’ Case: When using
switchorif...elseif, it’s good practice to include a finalelseorotherwiseblock to handle any unexpected values. This makes your code more robust. - Compare Floating-Point Numbers Carefully: Due to how computers store floating-point numbers, using
==for direct comparison can be unreliable. For example,0.1 + 0.2 == 0.3isfalse! Instead, check if the absolute difference is within a small tolerance:if abs(a - b) < 1e-9.
Common Errors and Debugging Tips
Section titled “Common Errors and Debugging Tips”- Assignment vs. Comparison: A very common mistake is using the assignment operator
=instead of the comparison operator==inside anifcondition (e.g.,if x = 5). The MATLAB Editor will usually flag this with a warning. - Missing
endKeyword: Everyif,switch,for, andwhileblock must be closed with anendkeyword. The MATLAB Editor helps by auto-indenting and highlighting matching keywords, making it easier to spot a missingend. - Strings vs. Character Vectors: In older MATLAB code, you’ll see single quotes (
'text') for character vectors. Modern MATLAB heavily favors double quotes ("text") forstringobjects, which are more flexible. Be aware of the type when making comparisons.