Click4Ai

50.

Medium

Write a function matrix_rank(A) that computes the rank of a matrix. The rank is the number of linearly independent rows (or columns). Use SVD: rank = number of non-zero singular values.

Example:

Input: A = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

Output: 2

**Explanation:** Row 3 = 2*Row2 - Row1, so only 2 independent rows → rank = 2.

Constraints:

  • A can be any m×n matrix
  • Use a tolerance of 1e-10 for near-zero singular values
  • Return an integer
  • Test Cases

    Test Case 1
    Input: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
    Expected: 2
    Test Case 2
    Input: [[1, 0], [0, 1]]
    Expected: 2
    Test Case 3
    Input: [[1, 2], [2, 4]]
    Expected: 1
    + 2 hidden test cases