简体   繁体   English

知道传递给函数的参数是矢量还是矩阵

[英]Know whether argument passed to function is a vector or a matrix

I'm writing a function in Sage that should work in different way for vectors and matrices. 我正在Sage中编写一个函数,该函数应以不同的方式处理向量和矩阵。

I can not use isinstance function because type of vector or matrix depends on the type of the elements: 我不能使用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'>

What is the best way to distinguish vectors and matrices? 区分向量和矩阵的最佳方法是什么?

The solution was accidentally found while trying to find definition matrix.dim in the Sage source. 尝试在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")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM