Skip to content
Advertisement

Finding the minimum of the N numpy matrices?

I want to find the minimum of N numpy matrices elementwise (but with a twist, read till the end). To show, I create 3 numpy matrices as follows:

>>> a = np.random.randint(100, size=(3,3))
>>> b = np.random.randint(100, size=(3,3))
>>> c = np.random.randint(100, size=(3,3))
>>> a
array([[79,  7, 71],
       [14, 34, 68],
       [98, 97,  6]])
>>> b
array([[28, 25, 95],
       [69, 46, 39],
       [90, 11, 21]])
>>> c
array([[56,  3, 67],
       [44, 41, 44],
       [66, 25, 42]])

I except my output d to be:

d = array([[28,  3, 67],
         [14, 34, 39],
         [66, 11,  6]])

I also need to retain the information from where does the each element in the d matrix is coming from. So if I label a, b, c as class 0, 1, 2. In the end I need to have a m matrix like this:

m = array([[1, 2, 2],
           [0, 0, 1],
           [2, 1, 0]])

I prefere no-loops based numpy approach.

Advertisement

Answer

To find the minimum numbers:

d = np.min([a, b, c], axis=0)

And their origins:

m = np.argmin([a, b, c], axis=0)
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement