MATLAB Data Types and Structures 3 — Questions and Answers
Question 1: What happens when you concatenate a `double` array and a `single` array using `[]` in MATLAB?
- An error is thrown
- The result is double
- The result is single (Correct answer)
- The result is int32
Correct answer: The result is single
When concatenating single and double arrays, MATLAB converts the result to single (lower precision wins to save memory).
Question 2: How do you add a new field `age` to an existing struct `s`?
- s.addfield('age', 30)
- addfield(s, 'age', 30)
- s.age = 30 (Correct answer)
- s{'age'} = 30
Correct answer: s.age = 30
Simply assigning `s.age = 30` dynamically adds the field `age` to the struct.
Question 3: What does `fieldnames(s)` return for a struct `s` with fields `x` and `y`?
- ['x','y']
- {'x';'y'} (Correct answer)
- struct('x','y')
- [x y]
Correct answer: {'x';'y'}
`fieldnames()` returns a cell array of character vectors containing the field names.
Question 4: Which statement correctly creates an empty cell array of size 3x2 in MATLAB?
- C = cell(3,2) (Correct answer)
- C = {}(3,2)
- C = zeros(3,2,'cell')
- C = cell[3,2]
Correct answer: C = cell(3,2)
The `cell(m,n)` function creates an m-by-n cell array where every cell contains an empty matrix.
Question 5: What is the purpose of `int8` versus `uint8` in MATLAB?
- They are identical
- int8 stores signed integers (-128 to 127); uint8 stores unsigned integers (0 to 255) (Correct answer)
- int8 is for integers; uint8 is for floating point
- uint8 is deprecated
Correct answer: int8 stores signed integers (-128 to 127); uint8 stores unsigned integers (0 to 255)
`int8` represents signed 8-bit integers (-128 to 127), while `uint8` represents unsigned 8-bit integers (0 to 255).
Question 6: How do you convert a character array `'hello'` to a string object in MATLAB R2016b+?
- string('hello') (Correct answer)
- str('hello')
- char2str('hello')
- text('hello')
Correct answer: string('hello')
The `string()` function converts character arrays, cell arrays of chars, and other types to string objects.
Question 7: What does `numel(C)` return for a 2x3 cell array `C`?
- 2
- 3
- 6 (Correct answer)
- The total bytes used
Correct answer: 6
`numel()` returns the total number of elements, which for a 2x3 array is 2×3 = 6.
What happens when you concatenate a `double` array and a `single` array using `[]` in MATLAB?