Skip to main content
Contents
Calc
Dark Mode Prev Next Profile
\(\newcommand\DLGray{\color{Gray}}
\newcommand\DLO{\color{BurntOrange}}
\newcommand\DLRa{\color{WildStrawberry}}
\newcommand\DLGa{\color{Green}}
\newcommand\DLGb{\color{PineGreen}}
\newcommand\DLBa{\color{RoyalBlue}}
\newcommand\DLBb{\color{Cerulean}}
\newcommand\ds{\displaystyle}
\newcommand\ddx{\frac{d}{dx}}
\newcommand\os{\overset}
\newcommand\us{\underset}
\newcommand\ob{\overbrace}
\newcommand\obt{\overbracket}
\newcommand\ub{\underbrace}
\newcommand\ubt{\underbracket}
\newcommand\ul{\underline}
\newcommand\tikznode[3][]
{\tikz[remember picture,baseline=(#2.base)]
\node[minimum size=0pt,inner sep=0pt,#1](#2){#3};
}
\newcommand\del{\nabla}
\newcommand\R{\mathbb{R}}
\newcommand\C{\mathcal{C}}
\newcommand\N{\mathcal{N}}
\newcommand\eps{\varepsilon}
\renewcommand\epsilon{\varepsilon}
\renewcommand\subset{\subseteq}
\newcommand\norm[1]{\|{#1}\|}
\newcommand\matrixbrackets[4][1]{
\draw (#3,#2) -- (\fpeval{#3+0.2},#2);
\draw (#3,#1) -- (#3 ,#2);
\draw (#3,#1) -- (\fpeval{#3+0.2},#1);
\draw (#4,#2) -- (\fpeval{#4-0.2},#2);
\draw (#4,#1) -- (#4 ,#2);
\draw (#4,#1) -- (\fpeval{#4-0.2},#1);
}
\tikzstyle{circle node 0}=[fill=white, draw=black, shape=circle, inner sep=0pt]
\tikzstyle{circle node 2}=[fill=white, draw=black, shape=circle, inner sep=2pt]
\tikzstyle{hrect node}=[fill=white, draw=black, inner sep=2pt, outer sep=3pt]
\tikzstyle{vrect node}=[fill=white, draw=black, inner sep=0pt, outer sep=0pt]
\tikzstyle{hidden node 0}=[inner sep=0pt, outer sep=0pt]
\tikzstyle{hidden node 2}=[fill=white, inner sep=2pt, outer sep=2pt]
\tikzstyle{rect node 1}=[fill=white, inner sep=2pt, outer sep=0pt]
\tikzstyle{rect node 2}=[fill=white, draw=black, inner sep=2pt, outer sep=0pt]
\newcommand{\lt}{<}
\newcommand{\gt}{>}
\newcommand{\amp}{&}
\definecolor{fillinmathshade}{gray}{0.9}
\newcommand{\fillinmath}[1]{\mathchoice{\colorbox{fillinmathshade}{$\displaystyle \phantom{\,#1\,}$}}{\colorbox{fillinmathshade}{$\textstyle \phantom{\,#1\,}$}}{\colorbox{fillinmathshade}{$\scriptstyle \phantom{\,#1\,}$}}{\colorbox{fillinmathshade}{$\scriptscriptstyle\phantom{\,#1\,}$}}}
\)
π§π»βπ» Class Activities π§π»βπ» Class Activities
These in-class activities focus on writing small MATLAB functions that use
if and
switch statements. Each activity includes multiple parts and asks you to reason about which branch executes.
1. Activity 1: Simple if-statement.
Use the coding area, below, to complete the following tasks. Each task builds on the previous one, so you can modify your code block as you go.
(a)
Define the variable x as 6, if use an if-statement to define the variable y according to the following rule:
Solution .
x = 6;
if x <= 9
y = 1;
else
y = 4;
end
fprintf('for x = %d, we set y to %d\n', x, y);
(b)
Change
x to
16 and rerun your code block.
Solution .
Just change the value of
x to
16 in the previous code block.
(c)
Next, define
x as a random integer between -5 and 15, using the command
randi([-5, 15]).
Rerun your code multiple times to see how the value of
y changes based on the random value of
x.
Solution .
Just change the value of
x to
randi([-5, 15]) in the previous code block.
(d)
Update your code to set y according to the following new rule:
Solution .
x = randi([-5, 15]);
if x >= 1 & x <= 9
y = 1;
else
y = 4;
end
fprintf('for x = %d, we set y to %d\n', x, y);
2. Activity 2: Updating a Variable with Conditionals.
Use the coding area, below, to complete the following tasks.
(a)
Suppose
num is a random integer between 0 and 20. Give the code that increases
num by 5 if it is greater than 10 and decreases it by 5 otherwise.
Solution .
nnum = randi([0, 20]);
fprintf('Starting num = %d\n', num);
if num > 10
num = num + 5;
else
num = num - 5;
end
fprintf('Updated num = %d\n', num);
(b)
Suppose
num is a
1 x 1 double. Give the code that increases
num by 5 if it is greater than 10, decreases
num by 5 if it is less than 10, and does nothing if
num is zero.
Solution .
If
x = 0, the below script runs the commands
x = x - 5 and
disp(x), outputting
-5. However, if
x = 10, only the
disp(x) command is run, producing an output of
10.
if x > 10
x = x + 5;
elseif x < 10
x = x - 5;
end
disp(x)
3. Activity 3: Sign Label Function.
Write a function that classifies a single number as positive, negative, or zero.
(a)
Create a function named
sign_label that takes one input
x and returns one output
label with the value
'positive',
'negative', or
'zero'.
Solution .
function label = sign_label(x)
if x > 0
label = 'positive';
elseif x < 0
label = 'negative';
else
label = 'zero';
end
end
(b)
Modify the function so it returns a second output named
code with values
1,
-1, or
0 that match the sign.
Solution .
function [label, code] = sign_label(x)
if x > 0
label = 'positive';
code = 1;
elseif x < 0
label = 'negative';
code = -1;
else
label = 'zero';
code = 0;
end
end
4. Activity 4: Freeze Alert Function.
Use a simple
if-statement to return a warning message from a temperature input.
(a)
Write a function named
freeze_alert that takes
tempC (a scalar temperature in Celsius) and
tempWarn (how close to freezing to warn) and returns
message. If
tempC is at or below
tempWarn, return
'Freeze warning'; otherwise return
'No warning'.
Solution .
function message = freeze_alert(tempC, tempWarn)
if tempC <= tempWarn
message = 'Freeze warning';
else
message = 'No warning';
end
end
(b)
Update the function to return a second output
isFreezing that is
true or
false along with the message.
Solution .
function [message, isFreezing] = freeze_alert(tempC, tempWarn)
if tempC <= 0
message = 'Freeze warning';
isFreezing = true;
elseif tempC <= tempWarn
message = 'Freeze warning';
isFreezing = false;
else
message = 'No warning';
isFreezing = false;
end
end
5. Activity 5: Ticket Price Function.
Write a function that uses
if-elseif-else to choose among several price brackets.
(a)
Create a function named
ticket_price that takes a scalar input
age (a single personβs age, in years) and returns
price using the rules below:
Age less than 13: price = 6
Age from 13 to 64: price = 12
Age 65 or older: price = 8
(b)
Modify the function so it returns a second output
group and handles invalid ages. If
age < 0, return
price = NaN and
group = 'invalid'.
6. Activity 6: Letter Grade Function.
Convert a numeric score to a letter grade using range-based conditions.
(a)
Write a function named
letter_grade that returns
'A',
'B',
'C',
'D', or
'F' for a scalar
score using the standard 90/80/70/60 cutoffs.
(b)
Add an input check so that scores outside
0 to
100 return
'invalid'.
(c)
Concept check: why must the
score >= 90 test appear before the
score >= 80 test?
7. Activity 7: Shipping Mode Switch.
Use a
switch statement to choose among discrete shipping options.
(a)
Create a function named
shipping_cost that takes a
mode input (
'S',
'E', or
'O') and returns a scalar
cost of 5, 12, or 20.
Solution .
function cost = shipping_cost(mode)
switch mode
case 'S'
cost = 5;
case 'E'
cost = 12;
case 'O'
cost = 20;
otherwise
cost = NaN;
end
end
(b)
Extend the function so it also accepts full words (
'standard',
'express', and
'overnight') in addition to the single-letter codes.
Solution .
function cost = shipping_cost(mode)
switch mode
case {'S', 'standard'}
cost = 5;
case {'E', 'express'}
cost = 12;
case {'O', 'overnight'}
cost = 20;
otherwise
cost = NaN;
end
end
(c)
Concept check: what happens when
mode = 'e' (lowercase), and why?
Solution .
The
otherwise branch runs and returns
NaN because
switch comparisons are case-sensitive, so
'e' does not match
'E'.
8. Activity 8: Day Type Switch.
Map a day number to weekday or weekend status using a
switch-statement.
(a)
Write a function named
day_type that takes an integer
dayNum (1 = Monday, 7 = Sunday). Return
'weekday' for 1--5 and
'weekend' for 6--7.
(b)
Update the function to return a second output named
isWeekend that is
true or
false for valid days.
(c)
Concept check: what should the function return for
dayNum = 0, and which branch handles it?
9. Activity 9: Thermostat Mode Switch.
Use a discrete numeric code to select a thermostat mode.
(a)
Create a function named
thermostat_mode that takes a numeric code:
0 for off,
1 for heat, and
2 for cool. Return the string
'off',
'heat', or
'cool'.
(b)
Extend the function to return a second output
setPoint. Use
68 for heat,
74 for cool, and
NaN for off or invalid codes.
10. Activity 10: Late Fee Function.
Use an
if-elseif-else chain to assign a fee based on how late something is.
(a)
Write a function named
late_fee that takes a single number
daysLate (the number of days late) and returns
fee according to the table below:
daysLate
fee
0 or less
0
1 to 3
5
3 to 7
15
\(\quad\) more than 7\(\quad\)
\(\quad\) 30\(\quad\)
(b)
Modify the function to return a second output
status with values according to the table below:
daysLate
fee
status
0 or less
0
on time
1 to 3
5
minor late
3 to 7
15
late
\(\quad\) more than 7\(\quad\)
\(\quad\) 30\(\quad\)
\(\quad\) very late\(\quad\)