Search code examples
wolfram-mathematicamathematical-optimization

Mathematica Not Saving Variable


I try to perform this nested loop but it is not working. It's not saving the result in each stage. But if I replace listInitial with Print[ ] I observer that all changes are made.

Any suggestions??

For[b = 1, b < 4, b = b + 1,
 For[a = 1, a < 4, a = a + 1,
  For[x = 1, x < 4, x = x + 1,
   For[z = 1, z < 4, z = z + 1, listInitial = 
    If[Random[] > psurvival, 
      ReplacePart[
       InitialMatrix[3, 3, 3, 3], {b, a, x, z} -> 
        InitialMatrix[3, 3, 3, 3][[b]][[a]][[x]][[z]] - 1], 
      InitialMatrix[3, 3, 3, 3], {b, a, x, z} -> 
       InitialMatrix[3, 3, 3, 3][[b]][[a]][[x]][[z]]]]]]]

listInitial // TableForm

Solution

  • Thanks guys. I found this solution: I think it's the easier one and it's working.

    SetAttributes[myFunction, Listable]
    myFunction[x_] := 
     If[Random[] > psurvival, If [x - 1 < 0 , x , x - 1], x]
     myFunction[InitialMatrix[3, 3, 3, 3]] // TableForm