MATLAB Matrix and Array Operations 2 — Questions and Answers
Question 1: What does the MATLAB expression `A(:, 2)` return for a 3×4 matrix A?
- The second row of A
- The second column of A (Correct answer)
- A scalar at position (2,2)
- A 1×4 row vector
Correct answer: The second column of A
The colon in the row index selects all rows, so `A(:, 2)` returns the entire second column as a column vector.
Question 2: Which MATLAB function returns the number of elements in an array regardless of its dimensions?
- length(A)
- ndims(A)
- numel(A) (Correct answer)
- size(A)
Correct answer: numel(A)
`numel(A)` returns the total number of elements, equivalent to prod(size(A)).
Question 3: What is the result of `[1 2; 3 4] .^ 2` in MATLAB?
- [1 4; 9 16] (Correct answer)
- [1 2; 3 4] * [1 2; 3 4]
- [1 8; 27 64]
- An error because ^ requires square brackets
Correct answer: [1 4; 9 16]
The element-wise power operator `.^` squares each element individually, yielding [1 4; 9 16].
Question 4: How do you delete the third row of matrix A in MATLAB?
- delete(A, 3, 'row')
- A(3) = []
- A(3, :) = [] (Correct answer)
- remove(A, 3)
Correct answer: A(3, :) = []
Assigning `[]` to a full row slice `A(3, :)` removes that row from the matrix.
Question 5: What does `linspace(0, 1, 5)` produce?
- [0 0.25 0.5 0.75 1] (Correct answer)
- [0 0.2 0.4 0.6 0.8]
- [0 0.5 1]
- [1 2 3 4 5]
Correct answer: [0 0.25 0.5 0.75 1]
`linspace(0, 1, 5)` creates 5 linearly spaced values from 0 to 1 inclusive: [0, 0.25, 0.5, 0.75, 1].
Question 6: In MATLAB, what is the output of `size([1 2 3; 4 5 6])`?
- 6
- [2 3] (Correct answer)
- [3 2]
- [1 2 3 4 5 6]
Correct answer: [2 3]
`size` returns a vector [rows, cols], so a 2×3 matrix returns [2 3].
Question 7: Which operator performs matrix multiplication (not element-wise) in MATLAB?
- .*
- .×
- * (Correct answer)
- ×
Correct answer: *
The `*` operator performs standard matrix multiplication, while `.*` performs element-wise multiplication.
What does the MATLAB expression `A(:, 2)` return for a 3×4 matrix A?