0
0
MATLABdata~20 mins

Function definition syntax in MATLAB - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
MATLAB Function Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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
A8
B35
CError: Undefined function or variable 'addTwoNumbers'.
D0
Attempts:
2 left
💡 Hint
Remember that the function adds the two input numbers.
Predict Output
intermediate
2: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);
end
AError: Too many output arguments.
B[4 7]
C[9 1]
D[1 9]
Attempts:
2 left
💡 Hint
The function returns the smallest and largest numbers in the array.
Predict Output
advanced
2: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;
end
A17
B16
CError: Nested functions are not allowed.
D5
Attempts:
2 left
💡 Hint
The inner function squares the input, then 1 is added.
Predict Output
advanced
2: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, '!'];
end
AHello, !<br>Hello, Alice!
BHello, Guest!<br>Hello, Alice!
CError: Not enough input arguments.
DHello, Guest!<br>Hello, Guest!
Attempts:
2 left
💡 Hint
Check how the function handles missing input arguments.
Predict Output
expert
2: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
end
A1
B10
C24
DError: Maximum recursion limit exceeded.
Attempts:
2 left
💡 Hint
Recall how factorial is calculated recursively.