简体   繁体   English

在 Python 中创建数组 N x 1?

[英]Creating arrays N x 1 in Python?

In MATLAB, one would simply say在 MATLAB 中,人们会简单地说

L = 2^8
x = (-L/2:L/2-1)';

Which creates an array of size LX 1.它创建了一个大小为 LX 1 的数组。

How might I create this in Python?我如何在 Python 中创建它?

I tried:我试过:

L = 2**8
x = np.arange(-L/2.0,L/ 2.0)

Which doesn't work.哪个不起作用。

干得好:

x.reshape((-1,1))

The MATLAB code produces a (1,n) size matrix, which is transposed to (n,1) MATLAB 代码生成一个 (1,n) 大小的矩阵,该矩阵被转置为 (n,1)

>> 2:5
ans =

   2   3   4   5

>> (2:5)'
ans =

   2
   3
   4
   5

MATLAB matrices are always 2d (or higher). MATLAB 矩阵始终为 2d(或更高)。 numpy arrays can be 1d or even 0d. numpy数组可以是 1d 甚至 0d。

https://numpy.org/doc/stable/user/numpy-for-matlab-users.html https://numpy.org/doc/stable/user/numpy-for-matlab-users.html

In numpy :numpy

arange produces a 1d array: arange产生一个一维数组:

In [165]: np.arange(2,5)
Out[165]: array([2, 3, 4])
In [166]: _.shape
Out[166]: (3,)

There are various ways of adding a trailing dimension to the array:有多种方法可以向数组添加尾随维度:

In [167]: np.arange(2,5)[:,None]
Out[167]: 
array([[2],
       [3],
       [4]])
In [168]: np.arange(2,5).reshape(3,1)
Out[168]: 
array([[2],
       [3],
       [4]])
 

numpy has a transpose, but its behavior with 1d arrays is not what people expect from a 2d array. numpy有一个转置,但它对一维数组的行为并不是人们对二维数组的期望。 It's actually more powerful and general than MATLAB's ' .它实际上比 MATLAB 的'更强大、更通用。

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

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