Python:区分行向量和列向量 [英] Python: Differentiating between row and column vectors

查看:84
本文介绍了Python:区分行向量和列向量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

python 中是否有区分行向量和列向量的好方法?到目前为止,我正在使用 numpy 和 scipy,到目前为止我看到的是如果我要给一个向量,说

from numpy import *向量 = 数组([1,2,3])

他们不能说天气我的意思是一行或一个列向量.此外:

array([1,2,3]) == array([1,2,3]).transpose()真的

这在现实世界"中是不真实的.我意识到来自上述模块的大多数向量函数不需要区分.例如 outer(a,b)a.dot(b) 但为了我自己的方便,我想区分一下.

解决方案

您可以通过向数组添加另一个维度来明确区分.

<预><代码>>>>a = np.array([1, 2, 3])>>>一种数组([1, 2, 3])>>>a.转置()数组([1, 2, 3])>>>a.dot(a.transpose())14

现在强制它是一个列向量:

<预><代码>>>>a.shape = (3,1)>>>一种数组([[1],[2],[3]])>>>a.转置()数组([[1, 2, 3]])>>>a.dot(a.transpose())数组([[1, 2, 3],[2, 4, 6],[3, 6, 9]])

另一种选择是使用 np.newaxis 进行区分:

<预><代码>>>>a = np.array([1, 2, 3])>>>一种数组([1, 2, 3])>>>[:, np.newaxis]数组([[1],[2],[3]])>>>a[np.newaxis, :]数组([[1, 2, 3]])

Is there a good way of differentiating between row and column vectors in python? So far I'm using numpy and scipy and what I see so far is that If I was to give one a vector, say

from numpy import *
Vector = array([1,2,3])

they wouldn't be able to say weather I mean a row or a column vector. Moreover:

array([1,2,3]) == array([1,2,3]).transpose()
True

Which in "real world" is simply untrue. I realize that most of the functions on vectors from the mentioned modules don't need the differentiation. For example outer(a,b) or a.dot(b) but I'd like to differentiate for my own convenience.

解决方案

You can make the distinction explicit by adding another dimension to the array.

>>> a = np.array([1, 2, 3])
>>> a
array([1, 2, 3])
>>> a.transpose()
array([1, 2, 3])
>>> a.dot(a.transpose())
14

Now force it to be a column vector:

>>> a.shape = (3,1)
>>> a
array([[1],
       [2],
       [3]])
>>> a.transpose()
array([[1, 2, 3]])
>>> a.dot(a.transpose())
array([[1, 2, 3],
       [2, 4, 6],
       [3, 6, 9]])

Another option is to use np.newaxis when you want to make the distinction:

>>> a = np.array([1, 2, 3])
>>> a
array([1, 2, 3])
>>> a[:, np.newaxis]
array([[1],
       [2],
       [3]])
>>> a[np.newaxis, :]
array([[1, 2, 3]])

这篇关于Python:区分行向量和列向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆