-1

I am finding equivalent numpy expression which is equivalent to MATLAB expression like this:

[1: (arr(foo) - 1), (arr(foo) + 1): K];

where foo and K is integer, and arr is ndarray. I thought equivalent code is like this:

np.append(np.arange(0, arr[foo] - 1), np.arange((arr[foo]), K))

However, if K is 2 and arr.size is 2, these two expression is not identical. I think this is because MATLAB expression [1:1] returns 1, but np.arange(1,1) returns empty array.

How can I express above MATLAB code to Python3 code in efficient way?

percusse
  • 3,006
  • 1
  • 14
  • 28
Square
  • 149
  • 1
  • 8

1 Answers1

0

In an Octave session:

>> [1: (5-1), (5+1) : 10]
ans =
    1    2    3    4    6    7    8    9   10

In Ipython with numpy:

In [70]: np.r_[1:5, (5+1):(10+1)]
Out[70]: array([ 1,  2,  3,  4,  6,  7,  8,  9, 10])

np.r_ is a class with indexing method that uses np.arange and np.concatenate as in:

In [71]: np.concatenate([np.arange(1,5), np.arange(5+1, 10+1)])
Out[71]: array([ 1,  2,  3,  4,  6,  7,  8,  9, 10])

There are various cover functions for np.concatenate that manipulate the inputs, such as by adding dimensions, or raveling, etc.

The one that behaves most like the MATLAB [x y; z w] is np.block, which can concatenate lists recursively. Here, though, it's no different:

In [72]: np.block([np.arange(1,5), np.arange(5+1, 10+1)])
Out[72]: array([ 1,  2,  3,  4,  6,  7,  8,  9, 10])

And for completeness, a Python list version:

In [73]: list(range(1,5))+list(range(6,11))
Out[73]: [1, 2, 3, 4, 6, 7, 8, 9, 10]

I don't like append because it is misused so often. It isn't a clone of the list append. Without axis it ravels the first argument. It's ok for adding a scalar to a 1d array once, and that's about it.

hpaulj
  • 221,503
  • 14
  • 230
  • 353