MATLAB Variables and Workspace Interaction 2 — Questions and Answers
Question 1: Which command removes ALL variables from the MATLAB workspace without prompting for confirmation?
- clear all
- clear (Correct answer)
- clc
- delete all
Correct answer: clear
`clear` (with no arguments) removes all variables from the current workspace silently.
Question 2: What does the `whos` command display that `who` does not?
- Variable names only
- Size, bytes, and class of each variable (Correct answer)
- Only numeric variables
- Only global variables
Correct answer: Size, bytes, and class of each variable
`whos` provides detailed information including size, allocated bytes, and data class, while `who` lists only variable names.
Question 3: After executing `x = 5; y = x; x = 10;`, what is the value of `y`?
- 10
- 5 (Correct answer)
- undefined
- 0
Correct answer: 5
MATLAB uses value semantics for numeric types, so `y` receives a copy of `x` at the time of assignment and is unaffected by later changes to `x`.
Question 4: Which function checks whether a variable named 'myVar' exists in the current workspace?
- exist('myVar', 'var') (Correct answer)
- isvar('myVar')
- check('myVar')
- hasvar('myVar')
Correct answer: exist('myVar', 'var')
`exist('myVar', 'var')` returns 1 if `myVar` is defined in the current workspace and 0 otherwise.
Question 5: What is the result of assigning `A = [1 2; 3 4]; B = A;` and then modifying `B(1,1) = 99;`?
- A(1,1) becomes 99 too
- A remains [1 2; 3 4] (Correct answer)
- B becomes a reference to A
- An error is thrown
Correct answer: A remains [1 2; 3 4]
MATLAB uses copy-on-write semantics, so modifying `B` creates a separate copy, leaving `A` unchanged.
Question 6: What command saves only the variables `x` and `y` to a file named 'data.mat'?
- save data.mat x y (Correct answer)
- save('data.mat', x, y)
- export data.mat x y
- write('data.mat', x, y)
Correct answer: save data.mat x y
`save data.mat x y` saves only the specified variables `x` and `y` to 'data.mat'.
Question 7: How do you load only the variable 'score' from 'results.mat' into the workspace?
- load results.mat score
- load('results.mat', 'score')
- Both A and B are valid (Correct answer)
- import results.mat score
Correct answer: Both A and B are valid
Both the command syntax `load results.mat score` and the function syntax `load('results.mat', 'score')` are valid in MATLAB.
Which command removes ALL variables from the MATLAB workspace without prompting for confirmation?