简体   繁体   English

难以理解Python中的矩阵运算

[英]Difficulty understanding matrix operations in Python

Starting with an initial guess of a randomly created 4×4 binary matrix, write a code snippet that does the following over 100 iterations: 从对随机创建的4×4二进制矩阵的初始猜测开始,编写一个代码片段,该片段在100次迭代中执行以下操作:

  1. choose a random element of the matrix, and create a new matrix which is equal to the old matrix with one randomly chosen digit flipped (from 0 to 1, or vice versa); 选择矩阵的一个随机元素,并创建一个新矩阵,该矩阵等于旧矩阵,其中一个随机选择的数字翻转(从0到1,反之亦然);
  2. If the new matrix has smaller objective value than the old matrix, replace with the new matrix, otherwise, remain at the present matrix. 如果新矩阵的目标值小于旧矩阵的目标值,请替换为新矩阵,否则保留在当前矩阵上。

Print the final 4×4 matrix and the value of the determinant found at the end of 100 iterations. 打印最终的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

I am trying to improve my understanding of this code, if anyone could please check my comments after the hashtag #, I would be grateful. 我正在努力提高我对这段代码的理解,如果有人可以在#号标签后检查我的评论,我将不胜感激。

In particular I do not understand this this step: 特别是我不理解此步骤:

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

Thank you for any help in advance. 感谢您的任何帮助。

The step: 步骤:

If MNew[i,j] was 1 then MNew[i,j] is now 1 - 1 = 0. 如果MNew [i,j]为1,则MNew [i,j]现在为1-1 = 0。
If MNew[i,j] was 0 then Mnew[i,j] is now 1 - 0 = 1 如果MNew [i,j]为0,则Mnew [i,j]现在为1-0 = 1

So you see it is a way to flip the value from the previous iteration. 因此,您看到这是一种从上次迭代中翻转值的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM