【发布时间】:2016-08-23 06:47:35
【问题描述】:
编辑
我意识到我没有很好地检查我的 mwe,因此问了一些错误的问题。主要问题是当 numpy 数组作为 2d 数组而不是 1d 传入时(或者甚至当 python 列表作为 1d 而不是 2d 传入时)。所以如果我们有
x = np.array([[1], [2], [3]])
那么显然,如果您尝试对此进行索引,那么您将获得数组(如果您使用 item,则不使用)。这同样适用于标准的 Python 列表。
很抱歉让您感到困惑。
原创
我正在尝试从可能是 numpy 数组或标准 python 列表的东西中形成一个新的 numpy 数组。
例如
import numpy as np
x = [2, 3, 1]
y = np.array([[0, -x[2], x[1]], [x[2], 0, -x[0]], [-x[1], x[0], 0]])
现在我想形成一个函数,以便我可以轻松地制作y。
def skew(vector):
"""
this function returns a numpy array with the skew symmetric cross product matrix for vector.
the skew symmetric cross product matrix is defined such that
np.cross(a, b) = np.dot(skew(a), b)
:param vector: An array like vector to create the skew symmetric cross product matrix for
:return: A numpy array of the skew symmetric cross product vector
"""
return np.array([[0, -vector[2], vector[1]],
[vector[2], 0, -vector[0]],
[-vector[1], vector[0], 0]])
这很好用,我现在可以写了(假设包含上述函数)
import numpy as np
x=[2, 3, 1]
y = skew(x)
但是,我还希望能够在现有的 1d 或 2d numpy 数组上调用 skew。比如
import numpy as np
x = np.array([2, 3, 1])
y = skew(x)
不幸的是,这样做会返回一个 numpy 数组,其中的元素也是 numpy 数组,而不是我想要的 python 浮点数。
有没有一种简单的方法来形成一个新的 numpy 数组,就像我从 python 列表或 numpy 数组中所做的那样,结果只是一个标准的 numpy 数组,每个元素中都有浮点数?
现在显然一种解决方案是检查输入是否为 numpy 数组:
def skew(vector):
"""
this function returns a numpy array with the skew symmetric cross product matrix for vector.
the skew symmetric cross product matrix is defined such that
np.cross(a, b) = np.dot(skew(a), b)
:param vector: An array like vector to create the skew symmetric cross product matrix for
:return: A numpy array of the skew symmetric cross product vector
"""
if isinstance(vector, np.ndarray):
return np.array([[0, -vector.item(2), vector.item(1)],
[vector.item(2), 0, -vector.item(0)],
[-vector.item(1), vector.item(0), 0]])
else:
return np.array([[0, -vector[2], vector[1]],
[vector[2], 0, -vector[0]],
[-vector[1], vector[0], 0]])
但是,不得不到处编写这些实例检查变得非常乏味。
另一种解决方案是先将所有内容转换为数组,然后使用数组调用
def skew(vector):
"""
this function returns a numpy array with the skew symmetric cross product matrix for vector.
the skew symmetric cross product matrix is defined such that
np.cross(a, b) = np.dot(skew(a), b)
:param vector: An array like vector to create the skew symmetric cross product matrix for
:return: A numpy array of the skew symmetric cross product vector
"""
vector = np.array(vector)
return np.array([[0, -vector.item(2), vector.item(1)],
[vector.item(2), 0, -vector.item(0)],
[-vector.item(1), vector.item(0), 0]])
但我觉得这效率低下,因为它需要创建一个新的向量副本(在这种情况下没什么大不了的,因为向量很小,但这只是一个简单的例子)。
我的问题是,除了我所讨论的内容之外,是否有其他方法可以做到这一点,或者我是否坚持使用其中一种方法?
【问题讨论】:
-
您使用的是哪个 numpy 版本?对于 numpy 1.10.4,从数组中获取单个元素会返回标量而不是 numpy 数组,因此您的初始函数可以按照您的意愿工作。
-
我使用的是 1.10.4 @MSeifert,但是我在问题中犯了一个错误。主要问题是我使用二维数组来模拟列向量。我会解决这个问题。