MATLAB Matrix and Array Operations 4 — Questions and Answers
Question 1: What does logical indexing `A(A > 5)` return for matrix A = [1 6; 3 8]?
- A matrix with elements > 5 in place and zeros elsewhere
- A column vector [6; 8] (Correct answer)
- A logical mask [0 1; 0 1]
- An error
Correct answer: A column vector [6; 8]
Logical indexing selects elements satisfying the condition and returns them as a column vector in column-major order.
Question 2: What is the MATLAB operator for element-wise division?
- /
- \
- ./ (Correct answer)
- .\
Correct answer: ./
`./` divides corresponding elements of two arrays, whereas `/` performs matrix right division.
Question 3: What does `fliplr([1 2 3; 4 5 6])` return?
- [3 2 1; 6 5 4] (Correct answer)
- [4 5 6; 1 2 3]
- [6 5 4; 3 2 1]
- [1 4; 2 5; 3 6]
Correct answer: [3 2 1; 6 5 4]
`fliplr` flips the matrix left-to-right (reverses columns), producing [3 2 1; 6 5 4].
Question 4: What is the purpose of the backslash operator `A \ b` in MATLAB?
- Element-wise left division of A by b
- Solves the linear system Ax = b for x (Correct answer)
- Computes the left inverse of A
- Transposes A then divides by b
Correct answer: Solves the linear system Ax = b for x
`A \ b` uses Gaussian elimination to solve Ax = b, which is numerically preferred over `inv(A)*b`.
Question 5: How do you concatenate two matrices A (3×2) and B (3×3) horizontally in MATLAB?
- [A; B]
- [A, B] (Correct answer)
- horzcat(A, B) only
- concat(A, B, 2)
Correct answer: [A, B]
`[A, B]` or equivalently `horzcat(A, B)` concatenates matrices side by side, requiring the same number of rows.
Question 6: Which function returns the eigenvalues and eigenvectors of a square matrix A?
- svd(A)
- eig(A) (Correct answer)
- qr(A)
- lu(A)
Correct answer: eig(A)
`[V, D] = eig(A)` returns eigenvectors in columns of V and eigenvalues on the diagonal of D.
Question 7: What does `A(end, :)` select from matrix A?
- The last element of A
- The last column of A
- The last row of A (Correct answer)
- All elements from the end
Correct answer: The last row of A
`end` refers to the last index in that dimension, so `A(end, :)` selects all columns of the last row.
What does logical indexing `A(A > 5)` return for matrix A = [1 6; 3 8]?