1

Using Matlab you can modify an array from indices using vectorization :

A = [1, 2, 3, 4, 5, 6, 7, 8, 9]

Output :

A =

 1     2     3     4     5     6     7     8     9

Modifying :

A([2,4,6:9]) = -1

Output :

A =

 1    -1     3    -1     5    -1    -1    -1    -1

How can we do that using Numpy Python ?

3
  • 2
    A[np.r_[1,3,5:8]]=-1? Commented Apr 13, 2021 at 17:16
  • Thks Quang Hoang ! It works fine :-) ! Commented Apr 13, 2021 at 17:21
  • In effect np.r_ is doing the same thing as MATLAB [2,4,6:9], expanding and concatenating to create an array of individual indices. MATLAB wraps a lot of functionality in that [...] syntax. In python that syntax is restricted to lists and indexing (which is what r_ is 'pretending' to do!). Commented Apr 13, 2021 at 18:36

1 Answer 1

2

You can't combine a fancy integer index and a slice like that in numpy, so you have two options:

  1. Convert the slice to numerical indices:

    A = np.array([1,2,3,4,5,6,7,8,9])
    A[[1, 3, 5, 6, 7, 8]] = -1
    

    Notice the double square brackets: the index is a list of integers.

  2. Set the fancy index and slice separately:

    A[[1, 3]] = A[5:9] = -1
    

    Notice that the right bound of a slice is exclusive in python and indices are zero based.

Sign up to request clarification or add additional context in comments.

Comments

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.