Finds the rank of a matrix. Args: `matrix`: The matrix as a list of lists. Returns: The rank of the matrix. Example: >>> matrix1 = [[1, 2, 3], ... [4, 5, 6], ... [7, 8, 9]] >>> rank_of_matrix(matrix1) 2 >>> matrix2 =
(matrix: list[list[int | float]])
| 6 | |
| 7 | |
| 8 | def rank_of_matrix(matrix: list[list[int | float]]) -> int: |
| 9 | """ |
| 10 | Finds the rank of a matrix. |
| 11 | |
| 12 | Args: |
| 13 | `matrix`: The matrix as a list of lists. |
| 14 | |
| 15 | Returns: |
| 16 | The rank of the matrix. |
| 17 | |
| 18 | Example: |
| 19 | |
| 20 | >>> matrix1 = [[1, 2, 3], |
| 21 | ... [4, 5, 6], |
| 22 | ... [7, 8, 9]] |
| 23 | >>> rank_of_matrix(matrix1) |
| 24 | 2 |
| 25 | >>> matrix2 = [[1, 0, 0], |
| 26 | ... [0, 1, 0], |
| 27 | ... [0, 0, 0]] |
| 28 | >>> rank_of_matrix(matrix2) |
| 29 | 2 |
| 30 | >>> matrix3 = [[1, 2, 3, 4], |
| 31 | ... [5, 6, 7, 8], |
| 32 | ... [9, 10, 11, 12]] |
| 33 | >>> rank_of_matrix(matrix3) |
| 34 | 2 |
| 35 | >>> rank_of_matrix([[2,3,-1,-1], |
| 36 | ... [1,-1,-2,4], |
| 37 | ... [3,1,3,-2], |
| 38 | ... [6,3,0,-7]]) |
| 39 | 4 |
| 40 | >>> rank_of_matrix([[2,1,-3,-6], |
| 41 | ... [3,-3,1,2], |
| 42 | ... [1,1,1,2]]) |
| 43 | 3 |
| 44 | >>> rank_of_matrix([[2,-1,0], |
| 45 | ... [1,3,4], |
| 46 | ... [4,1,-3]]) |
| 47 | 3 |
| 48 | >>> rank_of_matrix([[3,2,1], |
| 49 | ... [-6,-4,-2]]) |
| 50 | 1 |
| 51 | >>> rank_of_matrix([[],[]]) |
| 52 | 0 |
| 53 | >>> rank_of_matrix([[1]]) |
| 54 | 1 |
| 55 | >>> rank_of_matrix([[]]) |
| 56 | 0 |
| 57 | """ |
| 58 | |
| 59 | rows = len(matrix) |
| 60 | columns = len(matrix[0]) |
| 61 | rank = min(rows, columns) |
| 62 | |
| 63 | for row in range(rank): |
| 64 | # Check if diagonal element is not zero |
| 65 | if matrix[row][row] != 0: |
nothing calls this directly
no outgoing calls
no test coverage detected