Logical variables: On Time or Delayed? Complete the function WhatIslt such that: The output logical variable onTime is true only if noTraffic is true and gasEmpty is false. The output logical variable delayed is false only if noTraffic is true and gasEmpty is false. Restriction: Logical expressions must be used. Do not use if statements. Function 1 function [onTime, delayed] = WhatIsIt (noTraffic, gasEmpty) 2 3 onTime = delaeyed = 4 end 5 Code to call your function 1 noTraffic=true; gasEmpty = true; 2 [onTime, delayed]=WhatIsIt (noTraffic, gasEmpty)
The Correct Answer and Explanation is:
Here is the correct version of the function using only logical expressions, without any if statements:
matlabCopyEditfunction [onTime, delayed] = WhatIsIt(noTraffic, gasEmpty)
onTime = noTraffic && ~gasEmpty;
delayed = ~(noTraffic && ~gasEmpty);
end
Explanation
This function evaluates whether a situation results in being “on time” or “delayed” based on two logical input conditions: noTraffic and gasEmpty. Each input is a logical variable (true or false).
To determine the output variable onTime, the expression must only return true if noTraffic is true and gasEmpty is false. This is achieved by the logical AND operation (&&) between noTraffic and the negation of gasEmpty. The negation is done using the logical NOT operator (~), which turns true into false and vice versa. So the condition becomes onTime = noTraffic && ~gasEmpty;. Only under this specific situation will onTime be true; in all other combinations, it evaluates to false.
The second output variable delayed is logically the opposite of onTime. According to the condition, delayed must be false only when noTraffic is true and gasEmpty is false, and true otherwise. Thus, delayed can be defined by simply negating the condition used for onTime. This is done using the logical NOT operator: delayed = ~(noTraffic && ~gasEmpty);.
This approach ensures that both conditions are computed using pure logical expressions and no conditional branching such as if statements, satisfying the problem’s constraint.
Example Call:
matlabCopyEditnoTraffic = true;
gasEmpty = true;
[onTime, delayed] = WhatIsIt(noTraffic, gasEmpty)
Output will be:
iniCopyEditonTime = false
delayed = true
This reflects the situation where, although there is no traffic, the gas tank is empty, resulting in a delay.
