Challenge - 5 Problems
Anonymous Functions Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of an anonymous function with vector input
What is the output of the following MATLAB code?
MATLAB
f = @(x) x.^2 + 2*x + 1; result = f([1 2 3]); disp(result);
Attempts:
2 left
💡 Hint
Remember that the operator .^ applies element-wise power to each element in the vector.
✗ Incorrect
The anonymous function computes (x^2 + 2*x + 1) element-wise. For x=1: 1+2+1=4, for x=2: 4+4+1=9, for x=3: 9+6+1=16.
❓ Predict Output
intermediate2:00remaining
Output of nested anonymous functions
What is the output of this MATLAB code?
MATLAB
g = @(x) x + 1; h = @(f, x) f(x) * 2; result = h(g, 3); disp(result);
Attempts:
2 left
💡 Hint
Evaluate the inner function g(3) first, then multiply by 2.
✗ Incorrect
g(3) = 3 + 1 = 4. Then h calls g(3) and multiplies by 2, so 4 * 2 = 8.
🔧 Debug
advanced2:00remaining
Identify the error in anonymous function definition
Which option will cause an error when defining the anonymous function in MATLAB?
Attempts:
2 left
💡 Hint
Check the operator used for power in MATLAB.
✗ Incorrect
MATLAB uses ^ for power, not **. Using ** causes a syntax error.
❓ Predict Output
advanced2:00remaining
Output of anonymous function with conditional expression
What is the output of this MATLAB code?
MATLAB
f = @(x) (x > 0) .* x + (x <= 0) .* 0; result = f([-2 0 3]); disp(result);
Attempts:
2 left
💡 Hint
The function returns x if x is positive, otherwise 0.
✗ Incorrect
For each element: if x>0, output x; else output 0. So -2 -> 0, 0 -> 0, 3 -> 3.
🧠 Conceptual
expert2:00remaining
Behavior of anonymous functions capturing variables
Consider the following MATLAB code. What is the value of y after running it?
MATLAB
a = 5; f = @(x) x + a; a = 10; y = f(3);
Attempts:
2 left
💡 Hint
Anonymous functions use the current value of workspace variables at the time of execution.
✗ Incorrect
The anonymous function looks up 'a' from the workspace when it is called. By then 'a' is 10, so f(3) = 3 + 10 = 13.