1

Below is the one I coded. The problem here is I have values 1, 2, and 3 in the A matrix and hence at the output A has all the values 1.
The result I expect is:

A = np.matrix([[1, 2, 2, 1], 
               [1, 1, 3, 1],
               [1, 1, 1, 3]]).

Any help is appreciated. Sorry for my poor writing. Thank you!

A = np.matrix([[1, 15, 23, 2], [3, 2, 56, 7], [2, 6, 8, 25]])
bound = np.array([1, 15, 25, 56])
for i in range(3, 0, -1):
    A[np.logical_and(bound[i - 1] <= A, A <= bound[i])] = i
8
  • numpy.searchsorted ? np.searchsorted(bound, A, side='left') Commented Aug 27, 2020 at 3:09
  • Thank you for your prompt response. The first element of the output matrix is 0. I expect there 1 Commented Aug 27, 2020 at 3:12
  • if 1 maps to 1, why 15 also maps to 1 ? shouldn't it be 2 ? Since there's a 15 in bound ? Commented Aug 27, 2020 at 3:13
  • But anyways, you can try np.searchsorted(bound, A, side='right') to see if it gives what you need. Commented Aug 27, 2020 at 3:15
  • Oh sorry for that!. Yes 15 must be 2. I tried with np.searchsorted(bound, A, side='right'). It doesn't work Commented Aug 27, 2020 at 3:15

1 Answer 1

1

One way of doing it is saving the changed elements in a separate mask_:

mask_ = np.ones_like(A, dtype=bool)
for i in range(3,0,-1):
    mask = np.logical_and(bound[i - 1] <= A, A <= bound[i])
    A[np.multiply(mask_,mask)] = i
    mask_ = np.multiply(mask_,~mask)

output:

[[1 2 2 1]
 [1 1 3 1]
 [1 1 1 3]]
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.