簡體   English   中英

在列后的矩陣列中查找最小值和值的索引

[英]Find min value and index of the value in a matrix column after column

我有一個問題,這似乎很容易,但它讓我很頭疼。 問題是我正在用 python 編程(我對它比較陌生),我正在尋找 matlab 中矩陣的函數max (min)的等價物,但使用的是numpy

我想要做的是獲取矩陣中的最小值及其索引

為了盡可能簡單地舉個例子,假設這是矩陣:

arr2D = np.array([[11, 12, 13, 34],
                  [14, 15, 16, 3],
                  [17, 15, 11, 1],
                  [7,   5, 11, 4],
                  [1,  12,  4, 4],
                  [12, 14, 15,-3]])

在matlab中我會這樣做:

[local_max, index] = min(arr2D)

我會得到矩陣中每一列的最小值及其索引。

嘗試使用以下代碼在 python 中重復相同的操作(在查看此處此處之后):

print(np.where(arr2D == np.amin(arr2D, axis = 0)))   # axis 0 is for columns

我得到以下輸出:

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

這不是我真正想要的!

預期的輸出應該是:

[1, 4]   # Meaning the minimum value is 1 and it is in row 4 for the first column
[5, 3]   # Meaning the minimum value is 5 and it is in row 3 for the second column
[4, 4]   # Meaning the minimum value is 4 and it is in row 4 for the third column
[-3, 5]  # Meaning the minimum value is -3 and it is in row 5 for the last column

我不能使用我得到的輸出:

print(np.where(arr2D == np.amin(arr2D, axis = 0)))

或者我不明白輸出或者這不是獲得 matlab 的等效函數max (min)的正確方法。

你可以幫幫我嗎?

更新:我忘了說矩陣是浮點數而不是整數。 我僅在示例中使用了整數

np.aminnp.min返回沿軸的最小值

np.amin(arr2D, axis=0)

出去:

array([ 1,  5,  4, -3])

np.argmin返回索引

np.argmin(arr2D, axis=0)

出去:

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

要獲得所需的輸出,您可以使用np.vstack並轉置數組

np.vstack([np.amin(arr2D, axis=0), np.argmin(arr2D, axis=0)]).T

出去:

array([[ 1,  4],
       [ 5,  3],
       [ 4,  4],
       [-3,  5]])

使用此代碼(您可以簡單地從中創建一個函數):

import numpy as np

arr2D = np.array([[11, 12, 13, 34],
            [14, 15, 16, 3],
            [17, 15, 11, 1],
            [7,   5, 11, 4],
            [1,  12,  4, 4],
            [12, 14, 15,-3]])

flat = arr2D.flatten()
arrayIndex = flat.tolist().index(min(flat))

// results
rowIndex = int(minIndex/arr2D.shape[0])
columnIndex = minIndex % arr2D.shape[1]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM