How to nest multiple parfor loops

MrAzzman already pointed out how to linearise nested loops. Here is a general solution to linearise n nested loops. 1) Assuming you have a simple nested loop structure like this: %dummy function for demonstration purposes f=@(a,b,c)([a,b,c]); %three loops X=cell(4,5,6); for a=1:size(X,1); for b=1:size(X,2); for c=1:size(X,3); X{a,b,c}=f(a,b,c); end end end 2) Basic linearisation using a for … Read more

Variable amount of nested for loops

Recursion can solve this problem neatly: function callManyTimes(maxIndices, func) { doCallManyTimes(maxIndices, func, [], 0); } function doCallManyTimes(maxIndices, func, args, index) { if (maxIndices.length == 0) { func(args); } else { var rest = maxIndices.slice(1); for (args[index] = 0; args[index] < maxIndices[0]; ++args[index]) { doCallManyTimes(rest, func, args, index + 1); } } } Call it like … Read more

Nested Loop Python

You’re incrementing count in the inner loop which is why you keep getting larger numbers before you want to You could just do this. >>> for i in range(1, 10): print str(i) * i 1 22 333 4444 55555 666666 7777777 88888888 999999999 or if you want the nested loop for some reason from __future__ … Read more

Creating N nested for-loops

You may use recursion instead with a base condition – void doRecursion(int baseCondition){ if(baseCondition==0) return; //place your code here doRecursion(baseCondition-1); } Now you don’t need to provide the baseCondition value at compile time. You can provide it while calling the doRecursion() method.

Is there a way to loop through a multidimensional array without knowing it’s depth?

Yes, you can use recursion. Here’s an example where you output all the elements in an array: function printAll($a) { if (!is_array($a)) { echo $a, ‘ ‘; return; } foreach($a as $v) { printAll($v); } } $array = array(‘hello’, array(‘world’, ‘!’, array(‘whats’), ‘up’), array(‘?’)); printAll($array); What you should always remember when doing recursion is that … Read more