Infinite nested loop in matlab
8 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
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 Kommentar
Antworten (1)
NVSL
am 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 Kommentare
Siehe auch
Kategorien
Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!