0

Starting with an initial guess of a randomly created 4×4 binary matrix, write a code snippet that does the following over 100 iterations:

  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);
  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.

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.

1 Answer 1

1

The step:

If MNew[i,j] was 1 then MNew[i,j] is now 1 - 1 = 0.
If MNew[i,j] was 0 then Mnew[i,j] is now 1 - 0 = 1

So you see it is a way to flip the value from the previous iteration.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.