Consider the following MATLAB code where a variable is reused. What will be the value of result after running this code?
x = 5; x = x + 3; result = x * 2;
Think about how the variable x changes step by step.
The variable x starts at 5, then 3 is added making it 8. Multiplying by 2 gives 16.
Look at this MATLAB code snippet. What will be the output of disp(a)?
a = 10; a = 'hello'; disp(a);
MATLAB variables can change type when reassigned.
The variable a is first a number, then overwritten with a string. The last value is displayed.
What error will this MATLAB code produce?
sum = 0; for i = 1:5 sum = sum + i; end average = sum / length; disp(average);
Check if all variables are defined before use.
The variable length is not defined, causing an error when used in division.
Consider this MATLAB code with nested functions. What will be printed?
function outer()
x = 10;
function inner()
x = 5;
disp(x);
end
inner();
disp(x);
end
outer();Think about variable scope inside nested functions.
Nested functions in MATLAB share the workspace of the outer function. However, assigning x = 5 inside inner creates a new local variable x that shadows the outer x. Thus, disp(x) inside inner prints 5, but the outer disp(x) prints 10.
Which of the following best explains why managing variable scope is important in MATLAB?
Think about how variables can affect each other in different parts of code.
Proper scope management prevents bugs and keeps code clear by controlling where variables can be accessed or changed.