0
0
MATLABdata~20 mins

Workspace and variable management in MATLAB - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Workspace Wizard
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
What is the output of this MATLAB code snippet?

Consider the following MATLAB commands executed in order:

clear all
x = 5;
y = 10;
clear x;
z = exist('x', 'var');

What is the value of z after running this code?

MATLAB
clear all
x = 5;
y = 10;
clear x;
z = exist('x', 'var');
A3
B0
C2
D1
Attempts:
2 left
💡 Hint

Recall that clear x removes variable x from the workspace.

Predict Output
intermediate
2:00remaining
How many variables remain after this code runs?

Given the following MATLAB commands:

a = 1;
b = 2;
c = 3;
clearvars -except a c;

How many variables are in the workspace after these commands?

MATLAB
a = 1;
b = 2;
c = 3;
clearvars -except a c;
A2
B1
C3
D0
Attempts:
2 left
💡 Hint

The clearvars -except command keeps only specified variables.

🔧 Debug
advanced
2:00remaining
Identify the error in this workspace management code

What error will this MATLAB code produce?

clear all
x = 10;
if exist('x')
    disp('x exists');
end
MATLAB
clear all
x = 10;
if exist('x')
    disp('x exists');
end
ANo error, prints 'x exists'
BSyntax error: missing second argument in exist
CRuntime error: undefined variable 'x'
DLogical error: exist returns 0 even if variable exists
Attempts:
2 left
💡 Hint

exist('x') without a second argument is valid and returns 1 for variables in the workspace.

Predict Output
advanced
2:00remaining
What is the output of this variable clearing sequence?

Consider this MATLAB code:

a = 1;
b = 2;
c = 3;
clear a b
vars = who;

What does vars contain after running this code?

MATLAB
a = 1;
b = 2;
c = 3;
clear a b
vars = who;
A{}
B{'a', 'b', 'c'}
C{'a', 'b'}
D{'c'}
Attempts:
2 left
💡 Hint

The clear command removes specified variables from the workspace.

🧠 Conceptual
expert
2:00remaining
Which command will save only variables starting with 'data' to a file?

You have variables data1, data2, temp in your workspace. Which MATLAB command saves only variables starting with 'data' to myfile.mat?

Asave('myfile.mat', '-except', 'temp')
Bsave('myfile.mat', 'data1', 'data2')
Csave('myfile.mat', '-regexp', '^data')
Dsave('myfile.mat', 'data*')
Attempts:
2 left
💡 Hint

Use the -regexp option to save variables matching a pattern.