Home > database >  Creating arrays N x 1 in Python?
Creating arrays N x 1 in Python?

Time:10-17

In MATLAB, one would simply say

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

Which creates an array of size L X 1.

How might I create this in Python?

I tried:

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

Which doesn't work.

CodePudding user response:

Here you go:

x.reshape((-1,1))

CodePudding user response:

The MATLAB code produces a (1,n) size matrix, which is transposed to (n,1)

>> 2:5
ans =

   2   3   4   5

>> (2:5)'
ans =

   2
   3
   4
   5

MATLAB matrices are always 2d (or higher). numpy arrays can be 1d or even 0d.

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

In numpy:

arange produces a 1d array:

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. It's actually more powerful and general than MATLAB's '.

  • Related