很难理解Python中的矩阵运算

2024-04-20 13:54:12 发布

您现在位置:Python中文网/ 问答频道 /正文

从一个随机创建的4的初始猜测开始×4二进制矩阵,编写一个代码段,在100次迭代中执行以下操作:

  1. 选择矩阵中的一个随机元素,创建一个新矩阵,该矩阵等于一个随机数字翻转的旧矩阵(从0到1,反之亦然)
  2. 如果新矩阵的目标值小于旧矩阵,则用新矩阵替换,否则,保留当前矩阵

打印最后4个×4在100次迭代结束时发现的矩阵和行列式的值

import numpy as np
MOld = np.random.randint(2, size=[4,4])
for j in range(100): #for loop over 100 iterations
    MNew = np.array(MOld) #new matrix equal to old matrix
    i,j = np.random.randint(4), np.random.randint(4) #choosing random elements of the matrix.
    MNew[i,j] = 1 - MNew[i,j] #do not understand this
    if f(MNew) < f(MOld): #if new matrix < old matrix
        MOld = MNew #replacing value

print(MOld) #printing original 4x4 matrix
print(f(MOld)) #printing determinant value

我正在努力提高我对这段代码的理解,如果有人能在标签#后查看我的评论,我将不胜感激

我尤其不明白这一步:

MNew[i,j]=1-MNew[i,j]

提前谢谢你的帮助


Tags: newforifvaluenp二进制矩阵random