MATLAB by Example: Conditionals
Conditional logic uses `if`, `elseif`, and `else`. This sample demonstrates decision making based on values.
Code
x = rand(); % Random number between 0 and 1
if x > 0.8
disp('High value');
elseif x > 0.5
disp('Medium value');
else
disp('Low value');
end
% Switch statement
grade = 'B';
switch grade
case 'A'
disp('Excellent');
case 'B'
disp('Good');
case {'C', 'D'}
disp('Fair');
otherwise
disp('Unknown');
endExplanation
The if statement allows you to execute code based on logical conditions. The syntax involves if, optional elseif blocks, an optional else block, and a final end. Conditions usually involve comparison operators like == (equal), ~= (not equal), <, >, and logical operators like && (AND) and || (OR).
For checking a variable against a set of discrete values, the switch statement is often cleaner than a long chain of elseifs. You provide an expression to the switch keyword and define case blocks for matching values. You can match multiple values in a single case by enclosing them in a cell array (curly braces).
An otherwise block in a switch statement acts like the else in an if statement, catching any values that didn't match previous cases. This is useful for error handling or providing default behavior.
Code Breakdown
if x > 0.8 starts the conditional block.case {'C', 'D'} matches if grade is either 'C' or 'D'.
