-1

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.

Dimitri_896
  • 137
  • 4

2 Answers2

1

Here you go:

x.reshape((-1,1))
sehan2
  • 1,700
  • 1
  • 10
  • 23
1

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 '.

hpaulj
  • 221,503
  • 14
  • 230
  • 353