2012-01-05 72 views
0

我正在为Sage写一个函数,该函数应该以不同的方式用于向量和矩阵。知道传递给函数的参数是向量还是矩阵

我不能使用isinstance功能,因为矢量或矩阵的类型取决于元素的类型:

sage: type(matrix([[1]])) 
<type 'sage.matrix.matrix_integer_dense.Matrix_integer_dense'> 
sage: type(matrix([[i]])) 
<type 'sage.matrix.matrix_symbolic_dense.Matrix_symbolic_dense'> 

什么是区别矢量和矩阵的最佳方式?

+2

只需用'matrix.dim'检查尺寸 – 2012-01-05 11:27:06

+0

@DavidZwicker,你能解释什么是'matrix.dim'以及如何使用它? – 2012-01-05 12:50:28

回答

1

该解决方案意外发现,同时试图在Sage来源中找到定义matrix.dim

from sage.matrix.matrix import is_Matrix 
from sage.structure.element import is_Vector 

def myfunction(x): 
    if is_Vector(x): 
     # do something 
    elif is_Matrix(x): 
     # do something else 
    else: 
     raise TypeError("The argument must be vector or matrix")