Challenge - 5 Problems
Local Functions Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of a script with local function call
What is the output of this MATLAB script when run?
MATLAB
disp(mainFunction())
function out = mainFunction()
out = helperFunction(5);
end
function y = helperFunction(x)
y = x^2;
endAttempts:
2 left
💡 Hint
Local functions can be called by functions in the same file.
✗ Incorrect
The mainFunction calls helperFunction with input 5. helperFunction squares it, returning 25.
❓ Predict Output
intermediate2:00remaining
Value of variable after local function modifies it
What is the value of variable 'result' after running this code?
MATLAB
function result = testLocal()
x = 3;
result = increment(x);
function y = increment(a)
y = a + 2;
end
end
r = testLocal();Attempts:
2 left
💡 Hint
Local functions can access variables passed as arguments.
✗ Incorrect
The local function increment adds 2 to input 3, returning 5.
❓ Predict Output
advanced2:00remaining
Output when local function shadows variable
What is the output of this script?
MATLAB
function output = shadowTest()
x = 10;
output = localFunc();
function y = localFunc()
x = 5;
y = x + 1;
end
end
result = shadowTest();
disp(result)Attempts:
2 left
💡 Hint
Local function has its own variable 'x' that hides outer 'x'.
✗ Incorrect
Inside localFunc, x is set to 5, so y = 5 + 1 = 6.
❓ Predict Output
advanced2:00remaining
Output of a script with chained local function calls
What is the output of this MATLAB script when run?
MATLAB
disp(outsideCall())
function y = outsideCall()
y = localOnly();
end
function z = localOnly()
z = 42;
endAttempts:
2 left
💡 Hint
Local functions can call other local functions in the same file.
✗ Incorrect
The script calls outsideCall(), which calls localOnly() returning 42.
🧠 Conceptual
expert2:00remaining
Number of local functions accessible inside a nested function
Given this MATLAB file with three local functions, how many local functions can the nested function 'inner' call directly?
MATLAB
function main()
disp(inner())
function a = inner()
a = f1() + f2() + f3();
end
function x = f1()
x = 1;
end
function y = f2()
y = 2;
end
function z = f3()
z = 3;
end
endAttempts:
2 left
💡 Hint
Local functions in the same file are visible to each other.
✗ Incorrect
The nested function 'inner' can call all three local functions f1, f2, and f3 directly.