What is the output of the following MATLAB code?
function main
x = 5;
function nested()
x = 10;
disp(x)
end
nested();
disp(x)
end
mainRemember that nested functions share variables with their enclosing functions by default.
The nested function has its own local variable x which shadows the outer x. Assigning x = 10 inside the nested function does not modify the outer x. Therefore, the first disp(x) shows 10, and the second shows 5.
What will be displayed when running this MATLAB script?
for i = 1:3 disp(i) end
The disp function prints each value on a new line.
The loop runs from 1 to 3, and disp(i) prints each number on its own line.
What is the output of this MATLAB code?
function testClear
a = 7;
disp(a)
clear a
disp(a)
end
testClearThink about what happens when you clear a variable inside a function.
After clearing a, it no longer exists in the function workspace, so the second disp(a) causes an error.
What will be the output of this MATLAB code?
global x x = 3; function outer() global x x = 5; function inner() global x x = 10; disp(x) end inner(); disp(x) end outer(); disp(x)
Global variables are shared across functions and nested functions.
All functions access the same global x. The inner function sets it to 10, which is displayed three times.
Consider a MATLAB script that defines a variable a = 1 in the base workspace, then calls a function that also defines a = 2 and displays it. After the function call, the script displays a. Which statement is true?
Think about how MATLAB handles variable scope between base workspace and functions.
Variables inside functions have their own workspace and do not affect variables in the base workspace unless explicitly returned or declared global.
