MATLAB Variables and Workspace Interaction 4 — Questions and Answers
Question 1: What does the `-v7.3` flag do in the `save` command?
- Saves in ASCII text format
- Enables saving variables larger than 2 GB using HDF5 format (Correct answer)
- Compresses the file with gzip
- Saves only double-precision variables
Correct answer: Enables saving variables larger than 2 GB using HDF5 format
The `-v7.3` flag saves in HDF5-based format, which supports variables exceeding 2 GB, unlike the default format.
Question 2: How do you capture the contents of a .mat file into a struct without polluting the workspace?
- s = load('file.mat') (Correct answer)
- load('file.mat', '-struct')
- struct load('file.mat')
- import('file.mat') as s
Correct answer: s = load('file.mat')
When `load` is called with an output argument in function syntax, it returns a struct whose fields correspond to the saved variables.
Question 3: What is the class of a variable created by `x = 5` in MATLAB by default?
- int32
- single
- double (Correct answer)
- float
Correct answer: double
Numeric literals in MATLAB default to `double` (64-bit floating-point) unless explicitly cast to another type.
Question 4: Which function returns the number of bytes a variable occupies in memory?
- size(x)
- length(x)
- whos('x') — check Bytes column (Correct answer)
- memory(x)
Correct answer: whos('x') — check Bytes column
`whos` displays the bytes column for each variable; programmatically, `s = whos('x'); s.bytes` gives the byte count.
Question 5: What is the effect of suppressing output with a semicolon on a variable assignment like `x = 10;`?
- The variable is not stored
- The variable is stored but not printed to the Command Window (Correct answer)
- The variable is stored as read-only
- An error is generated
Correct answer: The variable is stored but not printed to the Command Window
A trailing semicolon suppresses the echo of the assignment to the Command Window but the variable is still created in the workspace.
Question 6: Which of the following correctly declares a global variable in a MATLAB function?
- global x = 5;
- global x; x = 5; (Correct answer)
- shared x; x = 5;
- x = global(5);
Correct answer: global x; x = 5;
The `global` keyword must appear on its own declaration line before the variable is used; assignment follows separately.
Question 7: What happens when you call `clear x` inside a function that has `x` declared as `persistent`?
- The persistent value is erased (Correct answer)
- The persistent variable is protected and not cleared
- An error is thrown
- The function is restarted
Correct answer: The persistent value is erased
`clear x` inside the function clears the persistent variable `x`; to clear persistent variables from outside, you use `clear functionName`.
What does the `-v7.3` flag do in the `save` command?