0
0
MATLABdata~20 mins

Local functions in MATLAB - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Local Functions Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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;
end
A10
B5
CError: Undefined function or variable 'helperFunction'.
D25
Attempts:
2 left
💡 Hint
Local functions can be called by functions in the same file.
Predict Output
intermediate
2: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();
AError: Undefined function 'increment'.
B3
C5
D2
Attempts:
2 left
💡 Hint
Local functions can access variables passed as arguments.
Predict Output
advanced
2: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)
A6
B11
CError: Variable 'x' is undefined.
D10
Attempts:
2 left
💡 Hint
Local function has its own variable 'x' that hides outer 'x'.
Predict Output
advanced
2: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;
end
A42
B0
CError: Function 'outsideCall' not found.
DError: Undefined function or variable 'localOnly'.
Attempts:
2 left
💡 Hint
Local functions can call other local functions in the same file.
🧠 Conceptual
expert
2: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
end
A0
B3
C1
D2
Attempts:
2 left
💡 Hint
Local functions in the same file are visible to each other.