| Contents | Index |
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.
You can nest any number of if statements. Each if statement requires an end keyword.
Avoid adding a space within the elseif keyword (else if). The space creates a nested if statement that requires its own end keyword.
Within an if or while expression, all logical operators, including | and &, short-circuit. That is, if the first part of the expression determines a true or false result, MATLAB does not evaluate the second part of the 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
endRespond 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)
endFind 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.')
endConcatenate 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 = [];
endTake advantage of short-circuiting to avoid error or warning messages:
x = 42;
if exist('myfunction.m') && (myfunction(x) >= pi)
disp('Condition is true')
end
| © 1984-2012- The MathWorks, Inc. - Site Help - Patents - Trademarks - Privacy Policy - Preventing Piracy - RSS |