MATLAB Data Types and Structures 5 — Questions and Answers
Question 1: What is the difference between `==` and `isequal()` when comparing arrays in MATLAB?
- They are identical
- `==` compares element-wise and returns an array; `isequal()` checks if arrays are identical and returns a scalar (Correct answer)
- `isequal()` only works on strings
- `==` only works on scalars
Correct answer: `==` compares element-wise and returns an array; `isequal()` checks if arrays are identical and returns a scalar
`==` performs element-wise comparison returning a logical array, while `isequal()` returns a single true/false for whole-array equality.
Question 2: What happens when you assign `s(5).x = 10` to a struct `s` that only has elements 1-3?
- An error is thrown
- Elements 4 and 5 are created with x=0
- Elements 4 and 5 are created; element 4 has empty fields and element 5 has x=10 (Correct answer)
- Only element 5 is created
Correct answer: Elements 4 and 5 are created; element 4 has empty fields and element 5 has x=10
MATLAB auto-expands struct arrays; intermediate elements (4) are created with empty (`[]`) field values.
Question 3: Which syntax correctly creates a string array (not cell array of chars) in MATLAB R2017a+?
- ["hello", "world"]
- {"hello", "world"}
- ["hello"; "world"]
- string({"hello","world"}) (Correct answer)
Correct answer: string({"hello","world"})
string({...}) converts a cell array of chars into a string array; double-quoted literals like "hello" also create string scalars.
Question 4: What does `sparse()` create in MATLAB?
- A compressed cell array
- A matrix that only stores nonzero elements to save memory (Correct answer)
- A struct with sparse fields
- An array with NaN padding
Correct answer: A matrix that only stores nonzero elements to save memory
`sparse()` creates a sparse matrix representation that stores only nonzero values and their indices, saving memory for large matrices with few nonzeros.
Question 5: How do you find all keys in a `containers.Map` object named `m`?
- m.keys
- keys(m) (Correct answer)
- m.Keys()
- fieldnames(m)
Correct answer: keys(m)
The `keys(m)` function returns a cell array of all keys in a `containers.Map` object.
Question 6: What is the result of `size(struct('a',1,'b',2))` in MATLAB?
- [1 2]
- [2 1]
- [1 1] (Correct answer)
- [1 3]
Correct answer: [1 1]
A single struct is a 1x1 struct array, so `size()` returns `[1 1]` regardless of the number of fields.
Question 7: Which MATLAB function converts a string `'3.14'` to the numeric double value 3.14?
- num()
- str2double() (Correct answer)
- parse()
- double()
Correct answer: str2double()
`str2double()` converts a string or char array representing a number to a double-precision value.
What is the difference between `==` and `isequal()` when comparing arrays in MATLAB?