[英]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)
的正確方法。
你可以幫幫我嗎?
更新:我忘了說矩陣是浮點數而不是整數。 我僅在示例中使用了整數
使用此代碼(您可以簡單地從中創建一個函數):
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.