Thursday, December 06, 2007

Nested for loops with recursion

Recently I had to use nested for loops to solve a problem but the number of these loops (n) had to be input:


I thought that recursion could be the answer. Since I am interested in recursion, I gave it a try. Below is a simple Matlab function that writes 'hello' 2^n times recursively, i.e. if n=3, it will write 8 'hello's. See if you understand the logic:


My real world problem involved n-dimensional linear interpolation which is too long for a blog post. Recursion is fascinating for the curiously minded, and at times life saving. Does anyone know a way to express n nested for loops without using recursion (n is input)?

No comments: