You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用SymPy检查矩阵是否为方阵并实现非方阵的ValueError异常抛出?

Checking if a SymPy Matrix is Square (and Raising an Error if Not)

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 16:22:36