Infinite nested loop in matlab
8 views (last 30 days)
Show older comments
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??
1 Comment
Answers (1)
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.
0 Comments
See Also
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!