Doubt
Doubt

Reputation: 1222

Translating arrays from MATLAB to numpy

I am defining an array of two's, with one's on either end. In MATLAB this can be acheived by

x = [1 2*ones(1,3) 1]

In Python, however, numpy gives something quite different:

import numpy
numpy.array([[1],2*numpy.ones(3),[1]])

What is the most efficient way to perform this MATLAB command in Python?

Upvotes: 1

Views: 173

Answers (2)

unutbu
unutbu

Reputation: 879391

In [33]: import numpy as np

In [34]: np.r_[1, 2*np.ones(3), 1]
Out[34]: array([ 1.,  2.,  2.,  2.,  1.])

Alternatively, you could use hstack:

In [42]: np.hstack(([1], 2*np.ones(3), [1]))
Out[42]: array([ 1.,  2.,  2.,  2.,  1.])

In [45]: %timeit np.r_[1, 2*np.ones(300), 1]
10000 loops, best of 3: 27.5 us per loop

In [46]: %timeit np.hstack(([1], 2*np.ones(300), [1]))
10000 loops, best of 3: 26.4 us per loop

In [48]: %timeit np.append([1],np.append(2*np.ones(300)[:],[1]))
10000 loops, best of 3: 28.2 us per loop

Thanks to DSM for pointing out that pre-allocating the right-sized array from the very beginning, can be much much faster than appending, using r_ or hstack on smaller arrays:

In [49]: %timeit a = 2*np.ones(300+2); a[0] = 1; a[-1] = 1
100000 loops, best of 3: 6.79 us per loop

In [50]: %timeit a = np.empty(300+2); a.fill(2); a[0] = 1; a[-1] = 1
1000000 loops, best of 3: 1.73 us per loop

Upvotes: 7

Sudip Kafle
Sudip Kafle

Reputation: 4391

Use numpy.ones instead of just ones:

numpy.array([[1],2*numpy.ones(3),[1]])

Upvotes: 0

Related Questions