代码功能:
获取一个二维矩阵中每行(列)中最小值(最大值)对应的“逻辑值矩阵”(不使用循环控制语句)。
对应于matlab中语句:
data==min(data)
或 data==max(data)
例如:
python实现代码:
import numpy as np
def getMatrixRowMaxMinIdx(data,mode='min'):
num = data.shape[0]
if mode=='min':
r_idx = np.argmin(data,axis=1).reshape(1,num)
if mode=='max':
r_idx = np.argmax(data,axis=1).reshape(1,num)
cor_idx = np.concatenate((np.arange(num).reshape(1,num), r_idx),axis=0)
cor_idx = cor_idx.tolist()
r_idx2 = np.zeros(data.shape)
r_idx2[cor_idx[0],cor_idx[1]] = 1
return r_idx2
def getMatrixColMaxMinIdx(data,mode='min'):
num = data.shape[1]
if mode=='min':
r_idx = np.argmin(data,axis=0).reshape(1,num)
if mode=='max':
r_idx = np.argmax(data,axis=0).reshape(1,num)
cor_idx = np.concatenate((r_idx, np.arange(num).reshape(1,num)),axis=0)
cor_idx = cor_idx.tolist()
r_idx2 = np.zeros(data.shape)
r_idx2[cor_idx[0],cor_idx[1]] = 1
return r_idx2
if __name__ == '__main__':
data = np.round(np.random.randn(5,10)*100)
print(data)
idx = getMatrixRowMaxMinIdx(data)
print(idx)
idx = getMatrixRowMaxMinIdx(data,'max')
print(idx)
print('')
idx = getMatrixColMaxMinIdx(data)
print(idx)
idx = getMatrixColMaxMinIdx(data,'max')
print(idx)
运行结果:
[[ -7. 76. -19. 47. 41. -71. -63. -74. -1. -39.]
[ -57. 33. -13. 116. 98. 9. -51. 78. 22. -94.]
[ 52. -7. -107. 59. -176. -68. -54. 89. -30. 168.]
[ -74. 61. -46. -76. -25. 10. 33. 109. 17. 53.]
[ -51. -150. 14. -32. 43. -9. -63. 144. 94. -167.]]
[[0. 0. 0. 0. 0. 0. 0. 1. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 0. 0. 1.]
[0. 0. 0. 0. 1. 0. 0. 0. 0. 0.]
[0. 0. 0. 1. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 0. 0. 1.]]
[[0. 1. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 1. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 0. 0. 1.]
[0. 0. 0. 0. 0. 0. 0. 1. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 1. 0. 0.]]
[[0. 0. 0. 0. 0. 1. 1. 1. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 1. 0. 1. 0. 0. 0. 1. 0.]
[1. 0. 0. 1. 0. 0. 0. 0. 0. 0.]
[0. 1. 0. 0. 0. 0. 0. 0. 0. 1.]]
[[0. 1. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 1. 1. 0. 0. 0. 0. 0.]
[1. 0. 0. 0. 0. 0. 0. 0. 0. 1.]
[0. 0. 0. 0. 0. 1. 1. 0. 0. 0.]
[0. 0. 1. 0. 0. 0. 0. 1. 1. 0.]]
【如果python的numpy中有类似于matlab中的简单写法,请知会一下,谢谢!】