0
$\begingroup$

What I want to do here is evaluate

For[k = 1; t = Frr[1, 0, k], k < 1000, k++, 
  If[k >= 3, Break[], t = Flatten[t]*Frr[1, 0, k + 1]]];
t

in which Frr[i, j, k] is a function I need to evaluate many times in this For-loop (three inputs: i, j and number to break — here it is 3. How can I define a function that takes the three variables I need to control the loop.

$\endgroup$
  • $\begingroup$ What are you actually doing here with this loop? What is Frr supposed to do? It might be possible to solve your problem without loops if you could maybe talk about the actual problem you have. $\endgroup$ – J. M. will be back soon Nov 4 '17 at 9:20
  • $\begingroup$ I tried to put them on, but it's too long to put. since Frr related three other functions. Anyway Frr is a function with regard to three variables and comes out a list of values. Is this useful or not? otherwise I will give you all my code. $\endgroup$ – Ivy Gao Nov 4 '17 at 9:33
  • 1
    $\begingroup$ It would really help if you could write out what output you want to get. Leave it in terms of Frr, if you want. Or create a simpler, dummy function in it's place. You might be looking for something like Flatten[Frr[1, 0, #]] Frr[1, 0, # + 1] & /@ Range[1, 3], or maybe something involving Fold or FoldList, but it's pretty hard to tell, I'm afraid. $\endgroup$ – aardvark2012 Nov 4 '17 at 10:31
3
$\begingroup$

For your particular example, you could just write

f0[i_, j_, kmax_] := Product[f[i, j, k], {k, kmax}]

then

f1[0, 1, 3]

f[0, 1, 1] f[0, 1, 2] f[0, 1, 3]

However, it more likely that your example is just a toy problem standing in for a more complicated one. Assuming that and also that you are committed to using For, then you might write

f1[i_, j_, kmax_] :=
  Module[{t},
    For[k = 1; t = f[i, j, 1], k < 1000, k++,
      If[k >= kmax, Break[], t = t f[i, j, k + 1]]];
    t]

f1[0, 1, 3]

f[0, 1, 1] f[0, 1, 2] f[0, 1, 3]

I really don't recommend the For-loop solution because it is very inefficient and verbose in Mathematica. Rather, I recommend using Nest.

f2[i_, j_, kmax_] := Module[{k = 1}, Nest[# f[i, j, k++] &, 1, kmax]]

f2[0, 1, 3]

f[0, 1, 1] f[0, 1, 2] f[0, 1, 3]

$\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.