Infinite nested loop in matlab

8 views (last 30 days)
elham eftekhari
elham eftekhari on 27 Jan 2020
Answered: NVSL on 29 Jan 2025
I want to write a program that user enter the value of n that is the number of nested loops. n is dynamic and can change by user (if n=3 then we should have 3 loops inside loop as the same below)
for i=1:100
for j=1:100-i
for k=1:100-i-j
i+j+k
end
end
end
how should i program this??

Answers (1)

NVSL
NVSL on 29 Jan 2025
I understand you are trying to have your number of for loops to be varying based on your input. The best way to achieve this is by recursion. You can have a function that recurses “n” times based on your input. Below is a possible implementation:
%e - end point(100), s - starting sum(0)
function f(e, s, n)
if n == 1
for i = 1:e
s+i
end
else
for i=1:e
f(e-i, s+i, n-1)
end
end
end
f(100, 0, 3)
This code essentially gives the same output as the code you provided. Please set the values of n and e to lower numbers, as higher values tend to exponentially increase processing time.

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!