Challenge - 5 Problems
MATLAB Function Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of a simple function call
What is the output of this MATLAB code when calling
result = addTwoNumbers(3, 5); disp(result);?MATLAB
function sum = addTwoNumbers(a, b) sum = a + b; end
Attempts:
2 left
💡 Hint
Remember that the function adds the two input numbers.
✗ Incorrect
The function
addTwoNumbers takes two inputs and returns their sum. Calling it with 3 and 5 returns 8.❓ Predict Output
intermediate2:00remaining
Output of a function with multiple outputs
What is the output of this MATLAB code snippet?
[minVal, maxVal] = findMinMax([4, 7, 1, 9]); disp([minVal, maxVal]);MATLAB
function [minVal, maxVal] = findMinMax(arr)
minVal = min(arr);
maxVal = max(arr);
endAttempts:
2 left
💡 Hint
The function returns the smallest and largest numbers in the array.
✗ Incorrect
The function returns the minimum and maximum values of the input array. For [4,7,1,9], min is 1 and max is 9.
❓ Predict Output
advanced2:00remaining
Output of a nested function call
What is the output of this MATLAB code?
result = outerFunction(4); disp(result);MATLAB
function out = outerFunction(x)
function y = innerFunction(z)
y = z^2;
end
out = innerFunction(x) + 1;
endAttempts:
2 left
💡 Hint
The inner function squares the input, then 1 is added.
✗ Incorrect
The inner function squares 4 to get 16, then outerFunction adds 1, resulting in 17.
❓ Predict Output
advanced2:00remaining
Output of a function with default argument behavior
What is the output of this MATLAB code?
disp(greet()); disp(greet('Alice'));MATLAB
function message = greet(name)
if nargin == 0
name = 'Guest';
end
message = ['Hello, ', name, '!'];
endAttempts:
2 left
💡 Hint
Check how the function handles missing input arguments.
✗ Incorrect
If no input is given, the function sets name to 'Guest'. Otherwise, it uses the provided name.
❓ Predict Output
expert2:00remaining
Output of a recursive function
What is the output of this MATLAB code?
disp(factorialRecursive(4));MATLAB
function f = factorialRecursive(n)
if n == 0
f = 1;
else
f = n * factorialRecursive(n - 1);
end
endAttempts:
2 left
💡 Hint
Recall how factorial is calculated recursively.
✗ Incorrect
Factorial of 4 is 4*3*2*1 = 24. The function calls itself until n=0, then multiplies back up.