1
$\begingroup$

I am fitting using NonlinearModelFit, where I am trying to input guess values for parameters (g and xp1) from the for a loop. For a certain value of g or xp1, the loop takes infinitely long to compute and gets stuck. I want to skip to the next value of the loop after a certain time, say 5 seconds.

 pllcn22o = 
      Reap[For[g1 = -3, g1 < 6, g1 = g1 + 0.1,
         
         For[xp1 = -5, xp1 < 5, xp1 = xp1 + 0.5,
          pllcn22oo = 
           NonlinearModelFit[datal[2, tn, tend], 
            pllca22, {x0, f0, x1, f1, 
             x2, f2, {xp, xp1}, {g, g1}}, t, 
            MaxIterations -> 100000];
          If[ pllcn22oo["BIC"] < -1500 , 
           Sow[Join[{pllcn22oo["BIC"], "=g" g1, 
              pllcn22oo["BestFitParameters"]}]]]]]][[2]];
   pllcn22os= Sort[pllcn22o[[1]], #1[[1]] < #2[[1]] &]
    Export["pllc22o.mx", pllcn22os]
$\endgroup$
1
  • $\begingroup$ Wrap the code that gets stuck inside TimeConstrained with an appropriate time constraint. $\endgroup$
    – MarcoB
    Mar 28 at 18:05
0
$\begingroup$

Here is an example of MarcoB's suggestion:

AbsoluteTiming[
 TimeConstrained[Print[Pause[1]; 1], 3];
 TimeConstrained[Print[Pause[5]; 10], 3];
 TimeConstrained[Print[Pause[2]; 100], 3];
 ]

You can think of each Print statement as one iteration of the loop. Example output of the code:

1
100
{6.03724, Null}

This shows that it skipped the second Print statement when it took too long. The total time it took to run the code is 1 + 3 + 2 = 6 seconds. It would have taken 1 + 5 + 2 = 8 seconds but the second Print statement was interrupted after 3 seconds.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.