使用linspace和1创建Numpy矩阵(Create Numpy matrix using linspace and ones)

系统教程 行业动态 更新时间:2024-06-14 16:53:13
使用linspace和1创建Numpy矩阵(Create Numpy matrix using linspace and ones)

有了Numpy,我想我可以用这种方式创建一个矩阵

z = np.array( [np.linspace(0, 1, 2), np.ones((1, 2)), np.ones((1, 2))] )

然而,它给了我:

array([array([ 0., 1.]), array([[ 1., 1.]]), array([[ 1., 1.]])], dtype=object)

然后检查它的形状:

>>> z.shape (3,)

列维度不存在。 所以我想我有一个包含三个数组对象的数组。

如何在这里使用linespace()和ones()来获得3 x 2矩阵?

With Numpy, I thought I could create a matrix this way

z = np.array( [np.linspace(0, 1, 2), np.ones((1, 2)), np.ones((1, 2))] )

which, however, gives me:

array([array([ 0., 1.]), array([[ 1., 1.]]), array([[ 1., 1.]])], dtype=object)

then checking its shape:

>>> z.shape (3,)

The column dimension does not exist. So I think I got an array with three array objects.

How can I have the 3 x 2 matrix using linespace() and ones() here?

最满意答案

如果输入是1维的,你可以使用numpy.array :

np.array([np.linspace(0, 1, 2), np.ones((2,)), np.ones((2,))])

产量

array([[ 0., 1.], [ 1., 1.], [ 1., 1.]])

注意, np.ones((1,2))具有二维形状(1,2) ,而np.linspace(0, 1, 2)具有一维形状(2,) 。 要使用np.array创建所需的结果,数组需要具有兼容的形状 - 在这种情况下,这意味着使用1维数组np.ones(2,)而不是np.ones((1,2)) 。


如果你必须使用np.ones((1,2)) ,那么你也可以改为np.linspace(0, 1, 2) 2维,然后使用numpy.vstack :

np.vstack([np.linspace(0, 1, 2)[np.newaxis, :], np.ones((1,2,)), np.ones((1,2,))])

产量

array([[ 0., 1.], [ 1., 1.], [ 1., 1.]])

If the inputs are 1-dimensional, you could use numpy.array:

np.array([np.linspace(0, 1, 2), np.ones((2,)), np.ones((2,))])

yields

array([[ 0., 1.], [ 1., 1.], [ 1., 1.]])

Note that np.ones((1,2)) has a 2-dimensional shape (1,2), while np.linspace(0, 1, 2) has a 1-dimensional shape (2,). To create the desired result with np.array, the arrays need to have compatible shapes -- in this case, that means using the 1-dimensional array np.ones(2,) instead of np.ones((1,2)).


If you must use np.ones((1,2)), then you could instead make np.linspace(0, 1, 2) 2-dimensional as well, and then use numpy.vstack:

np.vstack([np.linspace(0, 1, 2)[np.newaxis, :], np.ones((1,2,)), np.ones((1,2,))])

yields

array([[ 0., 1.], [ 1., 1.], [ 1., 1.]])

更多推荐

本文发布于:2023-04-06 01:39:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/dzcp/e80d33d8387b841cdcfb5083ebe58739.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:矩阵   Numpy   linspace   Create   matrix

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!