MATLAB Variables and Workspace Interaction 3 — Questions and Answers
Question 1: Which of the following variable names is INVALID in MATLAB?
- myVar_1
- 1stValue (Correct answer)
- _score
- dataMatrix2
Correct answer: 1stValue
MATLAB variable names must begin with a letter; `1stValue` starts with a digit and is therefore invalid.
Question 2: What happens to a workspace variable if you declare a function with the same name in a script?
- The variable is overwritten
- MATLAB throws an error
- The function takes precedence over the variable during function calls (Correct answer)
- The variable persists and the function is ignored
Correct answer: The function takes precedence over the variable during function calls
In MATLAB's precedence order, functions defined in the current scope shadow workspace variables when called as functions.
Question 3: What is the maximum length of a MATLAB variable name?
- 31 characters
- 63 characters (Correct answer)
- 127 characters
- Unlimited
Correct answer: 63 characters
MATLAB variable names can be at most 63 characters long; characters beyond that are ignored.
Question 4: What does `save('backup.mat', '-append')` do when 'backup.mat' already exists?
- Overwrites the entire file
- Adds new variables without removing existing ones (Correct answer)
- Throws an error
- Creates a new file backup2.mat
Correct answer: Adds new variables without removing existing ones
The `-append` flag adds or updates variables in an existing .mat file without deleting variables that are already present.
Question 5: What is stored in the MATLAB variable `ans` after executing `3 + 4` without assigning the result?
- Nothing; `ans` is undefined
- 7 (Correct answer)
- 3
- An error message
Correct answer: 7
`ans` is a special MATLAB variable that automatically stores the result of the most recent expression not assigned to a named variable.
Question 6: After `load('data.mat')` is called, where do the variables from the file appear?
- In a separate file workspace
- In the current workspace (Correct answer)
- Only in the base workspace
- In a struct named 'data'
Correct answer: In the current workspace
By default, `load` places variables directly into the current (caller's) workspace.
Question 7: Which command would you use to rename a workspace variable from `oldName` to `newName`?
- rename oldName newName
- newName = oldName; clear oldName (Correct answer)
- move oldName newName
- alias newName oldName
Correct answer: newName = oldName; clear oldName
MATLAB has no `rename` command; the standard approach is to assign the value to a new name and then `clear` the old one.
Which of the following variable names is INVALID in MATLAB?