1

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?

2 Answers 2

7
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
Sign up to request clarification or add additional context in comments.

10 Comments

Thanks unutbu. In the future, how should I go about trying to find routines like this?
It should be noted though that r_ can be 4+ times slower than simply doing 2*ones(n+2) and then patching the edges. This won't be an issue unless it's in an inner loop, of course.
@DSM: Could you elaborate? Perhaps it depends on the version of numpy? I compared r_ with hstack and got roughly comparable results.
@unutbu: I mean versus a = 2*np.ones(3+2); a[0] = 1; a[-1] = 1;, which for me (1.6.2) is consistently about 4 times faster.
@Doubt: Experience helps. There is no shortcut. I learned a lot of numpy functions by just going through tutorials (like the numpy book), taking notes and writing example code snippets. If memory serves, I think I first saw r_ used here.
|
0

Use numpy.ones instead of just ones:

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

2 Comments

That will give a very different object, not array([1, 2, 2, 2, 1]) -- that's the OP's problem. (If the OP's code worked, probably a from numpy import * happened, or the OP simply copied the code incorrectly.)
Thanks, I have fixed this. Sorry for the confusion.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.