TransWikia.com

How do you stop a For loop from progressing until a condition has been met?

Mathematica Asked on August 31, 2021

I have a matrix and the generation of a number between 0 and 1 (this number will act as a probability):

matrix1 = {{1, 0, 7, 5}, {0, 1, 8, 0}, {7, 8, 0, 0}, {5, 0, 0, 1}};
prob = RandomReal[1]

I then have the following loop:

  For[q = 1, q <= 5, q++, {x = RandomInteger[{1, 4}];
  y = RandomInteger[{1, 4}];
  If[matrix1[[x, y]] == 0, matrix1[[x, y]] = 7, matrix1[[x, y]] = 0];
  Print[MatrixForm[matrix1]];
  probLoop = Print[RandomReal[1]];
  }]

A quick summary: The loop randomly picks an element position in matrix1, if there is a 0 in that position then 0 -> 7, if there’s a nonzero integer in that position then integer -> 0. The loop is currently set up so that it runs sequentially, starting from matrix1 we then generate a matrix2, 3, 4, 5 and 6 (each subsequent matrix is a build off of the ones before it) and an integer between 0 and 1 (more on this below).

Instead of running matrix1 continuously straight through the loop, I’d like to only continue the loop progression if the probability given by prob and probLoop allow for it.

In the example picture provided, we start with matrix1 and then through one iteration of the loop we’d have the creation of matrix2. The probability of matrix1 converting into matrix2 is given by prob(approx. 15% in this case). So 15% of the time the matrix is converted into matrix2 and the loop proceeds to the next round. If matrix1 fails to convert (approx. 85% chance), we just rerun matrix1 again to create a new matrix2 and a new probability for matrix conversion.

I would like to apply the above step-wise process for each loop iteration. So once we generate a matrix2, it’s only converted to matrix3 given by the percentage chance given by the first listed output of probLoop (matrix3 converts to 4 based upon the second given output of probLoop, etc). If matrix2 fails to update to matrix3 then matrix2 is just reran through the loop again to generate a new matrix3 with a new probability and this cycle repeats itself until matrix1 has converted into matrix6.

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP