Message Boards Message Boards

0
|
3898 Views
|
5 Replies
|
2 Total Likes
View groups...
Share
Share this post:

Code for a variable number of nested For functions?

Posted 3 years ago

Can code be written that specifies how many For statements will be nested as a variable x increases?

If x=3, we would nest three For statements with indices: istart, iend; jstart, jend, and kstart, kend.

If x=10, there would be 10 such terms all with different start and stop indices.

POSTED BY: Douglas Youvan
5 Replies
Posted 3 years ago

@Douglas: You can see an example of code that produces code here.

@Hans: That is what I would call an elegant solution.

POSTED BY: Mike Besso

Thank you all. This will take me a while to digest.

POSTED BY: Douglas Youvan

Basically there are two possibilities.

I you can replace your For - by Do- Loops this should work ( x ist the number of loops put into each other). Of course you could construct index with different end-points

x = 3;
index = Table[{i[j], 1, 2}, {j, 1, x}]
Do[
 Print[i[1], i[2], i[3]],
 Evaluate[Sequence @@ index]]

Or you could use

Lm = 3;       (* number of loops  *)
j = {2, 4, 3};  (*  end-points  *)


Clear[test]
test := Module[{},
  L = L + 1;
  If[L == 1 && a[[L]] == j[[L]], Return["end"]];
  If[L == Lm,

    If[a[[L]] == j[[L]],

    a[[L]] = 0;
    L = L - 2;
    test,

    a[[L]] = a[[L]] + 1;
    Print[a];
    nc = nc + 1; e1[[nc]] = a;
    L = L - 1;
    test
    ],

   If[a[[L]] == j[[L]],

    a[[L]] = 0;
    L = L - 2;
    test,

    a[[L]] = a[[L]] + 1;
    test
    ]
   ]
  ]

Now

L = nc = 0;
a = Table[0, {Lm}];
e1 = Table[0, {Times @@ j}];
test
POSTED BY: Hans Dolhaine

Thank you, Mike. The problem I am working on was solved years ago by what one might consider an elegant method. However, now that I think about it more, I would actually be interested in seeing some Mathematica code that writes Mathematica code.

POSTED BY: Douglas Youvan
Posted 3 years ago

Douglas:

I am sure a solution exists for this, as a last resort, you could write a function that generates the code and then executes the code. But, there is probably a more elegant solution.

Could you explain your use case? That additional information will help the community help you.

Have a great weekend.

POSTED BY: Mike Besso
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract