MATLAB - If End Statement
MATLAB - Conditional Control Flow: The if...end Statement
Section titled “MATLAB - Conditional Control Flow: The if...end Statement”In programming, we often need to execute different blocks of code based on certain conditions. MATLAB provides the if...end statement for this purpose. It allows your program to make decisions and follow different paths, forming the basis of conditional logic.
Syntax
Section titled “Syntax”The basic structure of a conditional block in MATLAB uses the if, elseif, else, and end keywords.
if <logical_expression_1> % Statement(s) to execute if logical_expression_1 is true
elseif <logical_expression_2> % Statement(s) to execute if logical_expression_1 is false % AND logical_expression_2 is true
else % Statement(s) to execute if all preceding expressions are false
end- An
ifblock can exist on its own. elseifandelseare optional and provide alternative paths.- You can have multiple
elseifblocks, but only oneelseblock. - The entire structure must be terminated by a single
endkeyword.
Flow Diagram
Section titled “Flow Diagram”You can visualize the logic flow as a series of questions:
Start | v+-------------------------+| Is condition_1 true? | --(Yes)--> [Execute Code Block 1] --++-------------------------+ | | (No) | v |+-------------------------+ || Is condition_2 true? | --(Yes)--> [Execute Code Block 2] --++-------------------------+ | | (No) | v |[Execute 'else' Block] -----------------------------------------+ | | v |End <-----------------------------------------------------------+Example: Classifying a Measurement
Section titled “Example: Classifying a Measurement”Let’s write a script that classifies a temperature reading. Create a script file named classifyTemperature.m and add the following code:
% Define a temperature in CelsiustemperatureC = 23.5;
% Check the condition and classify the temperatureif temperatureC < 0 classification = 'Freezing';elseif temperatureC >= 0 && temperatureC < 15 classification = 'Cold';elseif temperatureC >= 15 && temperatureC < 25 classification = 'Moderate';else % temperatureC >= 25 classification = 'Warm';end
% Display the result to the command window% The fprintf function formats and prints the output string.% %g is a placeholder for a floating-point number.% %s is a placeholder for a string.% \n creates a new line.fprintf('A temperature of %g C is considered %s.\n', temperatureC, classification);When you run this script from the MATLAB Command Window, it will display the following result:
A temperature of 23.5 C is considered Moderate.Best Practices and Modern Usage
Section titled “Best Practices and Modern Usage”Logical Short-Circuiting
Section titled “Logical Short-Circuiting”Always use && for logical AND and || for logical OR within if statements. These are “short-circuiting” operators. For A && B, MATLAB will not evaluate B if A is false. This is efficient and can prevent errors, for example, when checking if a variable exists before using it.
Vectorization over Loops
Section titled “Vectorization over Loops”MATLAB is optimized for array and matrix operations. While if statements are essential, avoid using them inside loops to process array elements one-by-one. Instead, use logical indexing. This is a core concept of idiomatic MATLAB programming and is significantly faster.
% --- SLOW: Using a loop with an if statement ---data = [-10, 5, 20, 30, -2];for i = 1:length(data) if data(i) < 0 data(i) = 0; % Replace negative values with 0 endend
% --- FAST: Using logical indexing (Vectorization) ---data = [-10, 5, 20, 30, -2];negative_indices = (data < 0);% The line above creates a logical array: [1, 0, 0, 0, 1]data(negative_indices) = 0; % Use the logical array to set values
% A more concise version of the above:data(data < 0) = 0;Common Errors and Debugging
Section titled “Common Errors and Debugging”- Assignment vs. Comparison: A very common mistake is using
=(assignment) instead of==(comparison) inside anifcondition. For example,if x = 5will cause an error. It should beif x == 5. - Floating-Point Comparison: Be careful when comparing floating-point numbers for exact equality due to precision limitations. Instead of
if x == 0.1, it’s safer to check if the difference is within a small tolerance:if abs(x - 0.1) < 1e-9. - Mismatched
end: Forgetting anendstatement or having too many will cause a syntax error. The MATLAB Editor is excellent at helping you find these by highlighting matching keywords and auto-indenting your code (Ctrl+IorCmd+I).