Creating Matrix from Two Arrays using Minimum of both

Viewed 174

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.

1 Answers

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.)

Related