Solution to Exercise 2 - nexthour Function

MATLAB Function Implementation
function hhout = chap4_prob2_nexthour(hhin)
%{
To test this function, you can use:
for n=1:14,
nnext = chap4_prob2_nexthour(n);
fprintf('Input: %d, Output: %d\n',n,nnext);
end
%}
hhout = mod( (hhin), 12 ) + 1;
end
Function Explanation:
Mathematical Logic:

The function uses the formula: hhout = mod(hhin, 12) + 1

Testing the Function:
% Test the function with hours 1 through 14
for n = 1:14
nnext = chap4_prob2_nexthour(n);
fprintf('Input: %d, Output: %d\n', n, nnext);
end

Expected Output: Hours 1→2, 2→3, ..., 11→12, 12→1, 13→2, 14→3

Alternative Implementations:
% Using if-else statement (more verbose)
function hhout = nexthour_alternative(hhin)
if hhin == 12
hhout = 1;
else
hhout = hhin + 1;
end
end

Note: The modulo approach is more elegant and handles edge cases better.



For more details, please contact me here.