Aconditional statement, or anif-then statement, is used to run a code segment only if some condition is met. It takes on the form “if A then B”. In MATLAB, the basicif-then statement looks like this:
If-then statement if logical expression
statements :
end
The set of statements are only run if logical expression is true.
Often, we want something different to happen when the logical expression is false. In this case, we may need anif-else statement. These take on the form
If-else statement if logical expression
statements A else
statements B end
Iflogical expressionis true, then the set of statements A are executed. If logical expression is not true, then the set of statements B are executed.
For example, you could write an M-file with the following code if 2==3
disp(’the statement is true’) else
disp(’the statement is false’) end
If you run it, you should see displayed
>> the statement is false since it is not true that 2 = 3.
Refer to Exercise A.0.16 for a basic example of conditional statements.
To write a conditional statement with more than two possibilities, we may want to use amultiple if-else statement. There are many variations, one of which is shown below:
Multiple if-else statement if logical expression 1
statements A
elseif logical expression 2 statements B
elseif logical expression 3 statements C
else
statements D end
For this example, if logical expression 1 is true, then statements A are executed. Otherwise, if logi- cal expression 2 is true, statements B are executed. If logical expression 1 and logical expression 2 are false, and logical expression 3 is true, thenstatements C are executed. If none of these logical expressions are true, then statements Dare executed. Note that only one set ofstatements A, B, C,andD are allowed
to be executed. Also, the very last else statement is not required, you may not want to do anything if none of the logical expression are true. There are many possible variations of multiple if-else statements.
One option you may wish to employ is to exit the conditional statement, for loop, or while loop if a condition is not met. In such cases, you may use the break or return commands. See help break for more information. The code segment below takes each number from 1 to 10 and displays whether it is divisible by 2, 3, or 5. However if the number is divisible by more than one of these then it only displays that it is divisible by the smallest of them. For example if i is 6 then it will display that it is divisible by 2 - but the following elseif statements are not checked.
n = 10;
for i = 1:n
if rem(i,2)==0
disp([num2str(i), ’ is divisible by 2’]) elseif rem(i,3)==0
disp([num2str(i), ’ is divisible by 3’]) elseif rem(i,5)==0
disp([num2str(i), ’ is divisible by 5’]) else
break end end
Notice the disp command has an argument that is written as entries of a row vector, separated by a comma.
The first entry uses the command num2str to change the numerical value of i to a string character so it can used in conjunction to the string statement ' is divisible by 2', for example.
See Exercise A.0.17 for practice with a combination of loops and conditional statements.
A switch statementis used when there are many conditions and we wish to make the code more simple to read. Suppose we have some variable and have a variety of code to run depending on its value. Each alternative for each particular value of the variable is called acase, and a different set of statements may be run for each alternative.
Switch statement switch variable case case A
statements A case case B
statements B
case {case C1, case C2, ...}
statements C otherwise
statements D end
Notes:
Any case may consist of multiple values of the variable, such as the one shown in the third case statement.
If no case expression matches the value of the variable, control passes to the otherwise case, if it exists.
Summary of MATLAB commands
MATLAB command What it does
x = some number Assigns a number to variable x
x = start:increment:end Assigns a vector of numbers to variable x. The first value isstart, and the subsequent values are obtained by taking increments of size increment, and the array ends when value end has been reached.
Example: x = 2:3:17 yields x = [2, 5, 8, 11, 14, 17]
A=[1 2 3; 4 5 6; 7 8 9] Assigns matrix
1 2 3 4 5 6 7 8 9
to variableA R = [1 2 3] Assigns the row vector [1 2 3] to variableR C = [1; 4; 7] Assigns the column vector
1 4 7
to variable C A(n,m) Outputanm (rownand column mofA)
A(n,:) Output rownofA
A(:,m) Output column mofA
size(A) Output the size of A in the form [# columns # rows]
A’ Computes the transpose of A
x*y Compute productxy
x.*y Computes element by element product
sqrt(x) Compute√
x
x^n Computexn
log(x),log10(x) Compute lnx, log10(x), respectively
abs(x) Compute absolute value |x|.
exp(x) Computeex
sin(x), cos(x), tan(x) Compute sin(x),cos(x),tan(x)
asin(x), acos(x), atan(x) Compute arcsin(x),arccos(x),arctan(x) floor(x) Compute floor (greatest integer below x) ceil(x) Compute ceiling (smallest integer above x) round(x) Round x to nearest integer
vpa(fraction) Converts fractions into decimal approximations
rref(A) ReducesAto row reduced echelon form (performs Gaussian elimi- nation)
inv(A) Computes the matrix inverseA−1
figure(n) Opens up figure number n (useful for working with multiple figures) hold on After running this line, any subsequent plot command is added to the current figure (instead of creating a new figure from scratch).
; Add the semicolon at the end of a line to suppress output to the command line. (Useful for speeding up code.)
ezplot(’cos(x)’) plot cos(x) with default window
ezplot(’cos(x)’,[xmin,xmax]) plot cos(x) on the interval xmin≤x≤xmax
ezplot(’cos(x)’,[xmin,xmax, plot cos(x) on the interval xmin≤x≤xmax, ymin≤y≤ymax ymin,ymax])
plot(x,y) Plot vector y against x
x < y Test logical expression x < y(returns 1 for true, 0 for false) x <= y Test logical expression x≤y (returns 1 for true, 0 for false) x == y Test logical expression x=y (returns 1 for true, 0 for false) x ~= y Test logical expression x6=y (returns 1 for true, 0 for false) format long Displays numbers with 15 decimal places
format short Displays numbers with 4 decimal places
MATLAB command What it does
for i=a:b For loop executes the code segment that follows, as variablei code segment increments fromatob.
end
whilelogical expression While loop executes the code segment that follows until code segment emphlogical expression is false.
end
for i=a:b For loop executes the code segment that follows, as variablei code segment increments fromatob.
end
iflogical expression If-then statement executes the code segment that follows, if code segment logical expression is true.
end
mod(q,d) Returns the remainder ifqis divided byd zeros(n,m) Make an×mmatrix of all zeros