Execute statements if condition is true
if expression statements elseif expression statements else statements end
if expression, statements, end evaluates an expression, and executes a group of statements when the expression is true.
elseif and else are optional, and execute statements only when previous expressions in the if block are false. An if block can include multiple elseif statements.
An evaluated expression is true when the result is nonempty and contains all nonzero elements (logical or real numeric). Otherwise, the expression is false.
Expressions can include relational operators (such as < or ==) and logical operators (such as &&, ||, or ~). MATLAB® evaluates compound expressions from left to right, adhering to operator precedence rules.
Note: Within the condition expression of an if or while statement, logical operators & and | behave as short-circuit operators. This behavior is the same as && and ||, respectively. Since && and || consistently short-circuit in if and while condition expressions and statements, it is good practice to use && and || instead of & and | within expression.
Assign to a matrix values that depend on their indices.
% Preallocate a matrix nrows = 10; ncols = 10; myData = ones(nrows, ncols); % Loop through the matrix for r = 1:nrows for c = 1:ncols if r == c myData(r,c) = 2; elseif abs(r - c) == 1 myData(r,c) = -1; else myData(r,c) = 0; end end end
Respond to command-line input. Because the input string could be more than one character, use strcmp rather than == to test for equality.
reply = input('Would you like to see an echo? (y/n): ', 's'); if strcmp(reply,'y') disp(reply) end
Find the indices of values in a vector that are greater than a specified limit.
A = rand(1,10); limit = .75; B = (A > limit); % B is a vector of logical values if any(B) fprintf('Indices of values > %4.2f: \n', limit); disp(find(B)) else disp('All values are below the limit.') end
Concatenate two variables when they are the same size. To avoid an error when the variables have different dimensions, compare the sizes using isequal rather than the == operator.
A = ones(2,3); % Two-dimensional array B = rand(3,4,5); % Three-dimensional array if isequal(size(A), size(B)) C = [A; B]; else warning('A and B are not the same size.'); C = ; end
Take advantage of short-circuiting to avoid error or warning messages.
x = 42; if exist('myfunction.m') && (myfunction(x) >= pi) disp('Condition is true') end