如何使用SymPy检查矩阵是否为方阵并实现非方阵的ValueError异常抛出?
Great question! The key difference here is how len() behaves for NumPy arrays vs. SymPy Matrices:
- For a NumPy
ndarray,len(V)returns the size of the first dimension (number of rows). - For a SymPy
Matrix,len(V)returns the total number of elements in the matrix—hence why your 2×2 matrix returns 4 instead of 2.
Solution 1: Using the shape Attribute
SymPy's Matrix.shape gives you a tuple (number_of_rows, number_of_columns), which is perfect for checking if the matrix is square. Here's how to implement the check:
from sympy import Matrix def validate_square_matrix(V): # Optional: First ensure we're dealing with a SymPy Matrix if not isinstance(V, Matrix): raise TypeError("Input must be a SymPy Matrix object") rows, cols = V.shape if rows != cols: raise ValueError('V is not a square matrix')
Example Usage:
# This will pass without issues square_mat = Matrix([[1,2],[3,4]]) validate_square_matrix(square_mat) # This will raise ValueError immediately non_square_mat = Matrix([[1,2,3],[4,5,6]]) validate_square_matrix(non_square_mat)
Solution 2: Using the Built-in is_square Property
SymPy actually has a handy built-in attribute for this exact check: Matrix.is_square. This approach is even more concise and readable:
def validate_square_matrix(V): if not isinstance(V, Matrix): raise TypeError("Input must be a SymPy Matrix object") if not V.is_square: raise ValueError('V is not a square matrix')
This property returns True automatically when the matrix has equal rows and columns, so you can skip unpacking the shape tuple entirely.
Either method works well—use shape if you need to access row/column counts for additional logic, or is_square for a cleaner, more direct check.
内容的提问来源于stack exchange,提问作者effmenz

