Home > database >  How to find the smallest value of element in matrix with size (9,2,2)
How to find the smallest value of element in matrix with size (9,2,2)

Time:01-10

Supposing I have a matrix A with the np.shape(A) = (9,2,2). Then, I would like to find the smallest element value for the inner matrix (2,2) of total 9 outer matrix. Let's call it B. Could anyone let me know what is the numpy code, please? Thank you in advance.

import numpy as np

A =np.array([[[24, 73],
             [35, 67]],

            [[35, 68],
            [21,  5]],

            [[29, 69],
            [60, 46]],

            [[98, 25],
            [50, 92]],

            [[63, 27],
            [55, 28]],

            [[60, 89],
            [61, 66]],

            [[87, 38],
            [44, 33]],

            [[64, 76],
            [76, 70]],

            [[90, 91],
            [71, 58]]])

np.shape(A)

Expected Result

B = [24,5,29,25,27,60,38,64,58]

np.shape(B) = (9,)

CodePudding user response:

Use min aggregating on the last two axes:

A.min((1, 2))

Alternatively, if you want a generic code to handle any number of dimensions, reshape then aggregate the min on the last dimension:

A.reshape(A.shape[0], -1).min(-1)

Output: array([24, 5, 29, 25, 27, 60, 33, 64, 58])

CodePudding user response:

min_list = [np.amin(A[i, :, :]) for i in range(A.shape[0])]

OR

min_list = np.amin(A.reshape(A.shape[0], A.shape[1]*A.shape[2]), axis=1)

CodePudding user response:

Since you wish only the get the code, there you go:

np.min(A, axis=(1,2))

CodePudding user response:

Solution

import numpy as np

A =np.array([[[24, 73],
             [35, 67]],

            [[35, 68],
            [21,  5]],

            [[29, 69],
            [60, 46]],

            [[98, 25],
            [50, 92]],

            [[63, 27],
            [55, 28]],

            [[60, 89],
            [61, 66]],

            [[87, 38],
            [44, 33]],

            [[64, 76],
            [76, 70]],

            [[90, 91],
            [71, 58]]])

B1 = A.min(axis=(1, 2))
B2 = np.min(A, axis=(1, 2))

print("B1 =", B1)
print("B2 =", B2)
print("np.shape(B1) =", np.shape(B1))

Find minimum value with 2 menthods

1.

B1 = A.min(axis=(1, 2))

2.

B2 = np.min(A, axis=(1, 2))

Find shape of array in numpy

shape = np.shape(B1)

Output

B1 = [24  5 29 25 27 60 33 64 58]
B2 = [24  5 29 25 27 60 33 64 58]
np.shape(B1) = (9,)
  • Related