Implement an arbitrary number N nested for loop
11 views (last 30 days)
In my project, I'm looking for a way to create a nested for loop up to a fixed number N, for my purpose, the N is an integer smaller than 300, therefore it's useful to create such a function. To explain it better my problem, i would illustrate with an example:
list_to_loop = [1,a,b,c]
% Psuedo code:
for i in list_to_loop:
for j in list_to_loop:
for k in list_to_loop:
I guess you already see the logic behind, in this example N = 3, i.e. I get a 3 layer nested for loop. I have seen answers to similar questions before but the answers were not general enough or its not very easy to understand because i come from a python background. Is there a very simple and elegant way to do this?
Walter Roberson on 8 Dec 2022
Is there a very simple and elegant way to do this?
There are relatively compact methods involving ndgrid() and cell arrays, but for N = 100, you will run out of memory.
I have posted source code for generalized looping that has very low memory overhead (as long as you do not try to save all of the outputs); see https://www.mathworks.com/matlabcentral/answers/109622-how-can-i-write-n-for-loops-just-by-a-single-command#answer_118218 . In the comment there, the second version I link to is an iterator for the case where the different slots can have different numbers of entries and different data types.