Starting with an initial guess of a randomly created 4×4 binary matrix, write a code snippet that does the following over 100 iterations:
- 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);
- 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.
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]
Thank you for any help in advance.