Conditional structures allow the state of the workspace to determine the flow of control in a function. The basic arithmetic conditional statement executes an associated code block only if the expression or condition evaluates to true . If the the condition evaluates to false , then the conditional structure passes control to the next code block defined by the structure or after the end of the structure.
Thus, the code block in the body of the conditional structure is executed only when the value of the expression in the condition statement resolves to true when the statement executes. This means that one will not know whether the code block of the condition structure will execute when writing the function. The state of the variables in the workspace will determine the value of the expression at runtime . When the condition resolves to true during execution we say that the condition is satisfied and the code block is executed. When the condition resolves to false during execution we say that the condition was not satisfied and the code block is skipped.
A conditional structure may contain more than one conditional statement ! A MATLAB conditional statement may utilize the elseif keyword or else keyword to supply the MATLAB interpreter with additional conditional code blocks. The elseif statement also requires a logical expression to determine the flow of execution of the conditional structure. An else statement has no expression and always executes its code block.
On the code block following the first true condition will be executed. All other code blocks will be skipped.
The flowchart
emphasizes that the algorithm consists of three mutually exclusive code blocks.
% Inputs should be numbers only
if ~all(isnumeric([a b c]))
error('%s: %s. %s', ...
'Error', 'Invalid expression', ...
'The input values must be real scalars.')
% Inputs should be real numbers (no complex polynomials!)
elseif ~all(isreal([a b c]))
error('%s: %s. %s', ...
'Error', 'Invalid expression', ...
'The input values must be real valued.')
% Compute the two roots
else
if abs(a) > eps
% Compute the discriminant once because it is required to
% determine both roots.
discriminant = sqrt(b^2 - 4*a*c);
% Calculate the two roots and assign the values to the vector x
x = (-b + [ discriminant; -discriminant ])./(2*a);
end
end
else
block executes only if the
if
block and
elseif
conditional expressions are
false
.
It is possible to include a conditional structure in any code block.
In MATLAB this would look similar to the following:
if (size(object) > BreadBoxSize)
if (size(object) > ToyotaCarolaSize)
disp('The object is an airplane!')
else
disp('The object is a motorcycle!')
end
else
if (size(object) > ShotGlassSize
disp('The object is a laptop!')
else
disp('The object is a smart watch!')
end
end
One may combine several conditional statements into one large conditional structure.
In MATLAB this would look similar to the following:
type = input('Animal, Mineral, or Vegetable?')
if strcmpi(type, 'Animal')
% Now we must guess animals
elseif strcmpi(type, 'Vegetable')
% Now we must guess vegetables
elseif strcmpi(type, 'Mineral')
% Now we must guess metal objects!
else
disp('Object must be animal, vegetable, or mineral!')
end
if
keyword and terminates with the
end
keyword.
false
.
When several conditional expressions test the same variable or value to determine the correct code block, one may use a switch structure. A switch structure evaluates a single expression and chooses one of several code blocks by testing the value in a conditional expression.
The MATLAB source code for a switch structure is similar to the following:
type = input('Animal, Mineral, or Vegetable?')
type = char(lower(type));
switch type
case 'animal'
% Now we must guess animals
case 'vegetable'
% Now we must guess vegetables
case 'mineral'
% Now we must guess metal objects!
otherwise
disp('Object must be animal, vegetable, or mineral!')
end
Notice that you need to convert your string to lower case and to a character array in case the user inputs a
string
"MINERAL"
instead of a character array
'vegetable'
.
It is possible to create a MATLAB switch structure that performs dissimilar comparisons upon a value. Consider our quadraticformula example.
Instead of using Nested if structures consider the following switch structure:
% variable p contains a 1xn array of coefficients for a polynomial of degree n-1
switch true
case ~isnumeric(p)
error('%s: %s. %s', 'Error', 'Invalid expression', ...
'The input values must be real scalars.')
case ~isreal(p)
error('%s: %s. %s', 'Error', 'Invalid expression', ...
'The input values must be real valued.')
case length(p)~=3
error('%s: %s. %s', 'Error', 'Invalid Array Size', ...
'There degree of the polynomial must be two.')
otherwise
% compute roots of quadratic polynomial
end
This is the type of implementation we are trying to achieve. The algorithm is clear from the structure of the source code. The switch structure communicates the purpose of each code block. This clarifies writing, reading, supporting the source code.
First create a flowchart and then create the M-file quadraticformula2.m that implements the following:
Write a new function
quadraticformula2
that improves upon
quadraticformula.m
.
Implement the nested conditions as a complex switch structure, and add a check for the length of the polynomial.
Use 2.2.8 and 2.2.9. Compute the root with the largest absolute value first, and then use multiplication instead of addition to determine the second root.
Compress your flowchart document and your M-file into a single file and submit it in Blackboard.
Your instructor will run your M-file quadraticformula2.m using randomly generated data and check to make sure it creates the appropriate response for both valid and invalid inputs.
Creative Commons Attribution-NonCommercial-ShareAlike 4.0
Attribution
You must give appropriate credit, provide a link to the license, and indicate if changes were made. You may do so in any reasonable manner, but not in any way that suggests the licensor endorses you or your use.
Noncommercial
You may not use the material for commercial purposes.
Share Alike
You are free to share, copy and redistribute the material in any medium or format. If you adapt, remix, transform, or build upon the material, you must distribute your contributions under the
same license
as the original.