2

Suppose I have the following (in python 3.7)

x = np.array([2,4,6])
y = np.array([3,5])

How can I obtain the output

np.array([[2, 2],
          [3, 4],
          [3, 5]])

Basically making use of the two arrays as the "axis" of my new matrix, and for each entry of the new matrix, take the min(row, col), without using any loops.

5
  • 1
    The expected output doesn't make much sense. Both arrays are of different sizes. which one will set the number of rows/cols? Commented Aug 23, 2020 at 9:48
  • I think .outer(x, y) will produce the array like the above, but with the entries being the multiplication of both. I'm looking for one that can take the minimum of both Commented Aug 23, 2020 at 9:49
  • 1
    np.minimum(*np.meshgrid(y,x)) Commented Aug 23, 2020 at 9:50
  • 1
    You can use outer any ufunc like minimum: np.minimum.outer(x,y) Commented Aug 23, 2020 at 9:54
  • @Brenlla That will work also. You could add another answer. Commented Aug 23, 2020 at 9:55

1 Answer 1

2

The function np.meshgrid will expand both of these input variables into 2d arrays (returning a 2-element list); you can then use np.minimum to obtain element-by-element minima:

np.meshgrid(y,x)

returns:

[
  array([[3, 5],
         [3, 5],
         [3, 5]]),
  array([[2, 2],
         [4, 4],
         [6, 6]])
]

and:

np.minimum(*np.meshgrid(y,x))

returns:

array([[2, 2],
       [3, 4],
       [3, 5]])

(Using * here to expand the list into two separate arguments to np.minimum.)

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.