“克隆"行或列向量 [英] "Cloning" row or column vectors
本文介绍了“克隆"行或列向量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有时,将行或列向量克隆"到矩阵很有用.通过克隆,我的意思是转换行向量,例如
Sometimes it is useful to "clone" a row or column vector to a matrix. By cloning I mean converting a row vector such as
[1,2,3]
放入矩阵
[[1,2,3]
[1,2,3]
[1,2,3]
]
或列向量(如
[1
2
3
]
进入
[[1,1,1]
[2,2,2]
[3,3,3]
]
在matlab或八度音阶中,这很容易做到:
In matlab or octave this is done pretty easily:
x = [1,2,3]
a = ones(3,1) * x
a =
1 2 3
1 2 3
1 2 3
b = (x') * ones(1,3)
b =
1 1 1
2 2 2
3 3 3
我想以numpy重复此操作,但未成功
I want to repeat this in numpy, but unsuccessfully
In [14]: x = array([1,2,3])
In [14]: ones((3,1)) * x
Out[14]:
array([[ 1., 2., 3.],
[ 1., 2., 3.],
[ 1., 2., 3.]])
# so far so good
In [16]: x.transpose() * ones((1,3))
Out[16]: array([[ 1., 2., 3.]])
# DAMN
# I end up with
In [17]: (ones((3,1)) * x).transpose()
Out[17]:
array([[ 1., 1., 1.],
[ 2., 2., 2.],
[ 3., 3., 3.]])
为什么第一种方法(In [16]
)不起作用?有没有办法以更优雅的方式在python中完成此任务?
Why wasn't the first method (In [16]
) working? Is there a way to achieve this task in python in a more elegant way?
推荐答案
这是一种优雅的Pythonic方式:
Here's an elegant, Pythonic way to do it:
>>> array([[1,2,3],]*3)
array([[1, 2, 3],
[1, 2, 3],
[1, 2, 3]])
>>> array([[1,2,3],]*3).transpose()
array([[1, 1, 1],
[2, 2, 2],
[3, 3, 3]])
[16]
的问题似乎是转置对数组没有影响.您可能想要一个矩阵:
the problem with [16]
seems to be that the transpose has no effect for an array. you're probably wanting a matrix instead:
>>> x = array([1,2,3])
>>> x
array([1, 2, 3])
>>> x.transpose()
array([1, 2, 3])
>>> matrix([1,2,3])
matrix([[1, 2, 3]])
>>> matrix([1,2,3]).transpose()
matrix([[1],
[2],
[3]])
这篇关于“克隆"行或列向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文