下面是我编码的那个。这里的问题是我在A矩阵中具有值1、2和3,因此在输出A处具有所有值1。
我期望的结果是:
A = np.matrix([[1, 2, 2, 1],
[1, 1, 3, 1],
[1, 1, 1, 3]]).
感谢您的帮助。对不起,我写得不好。谢谢!
A = np.matrix([[1, 15, 23, 2], [3, 2, 56, 7], [2, 6, 8, 25]])
bound = np.array([1, 15, 25, 56])
for i in range(3, 0, -1):
A[np.logical_and(bound[i - 1] <= A, A <= bound[i])] = i
答案 0 :(得分:1)
一种实现方法是将更改的元素保存在单独的mask_
中:
mask_ = np.ones_like(A, dtype=bool)
for i in range(3,0,-1):
mask = np.logical_and(bound[i - 1] <= A, A <= bound[i])
A[np.multiply(mask_,mask)] = i
mask_ = np.multiply(mask_,~mask)
输出:
[[1 2 2 1]
[1 1 3 1]
[1 1 1 3]]