Infinite nested loop in matlab

8 visualizaciones (últimos 30 días)
elham eftekhari
elham eftekhari el 27 de En. de 2020
Respondida: NVSL el 29 de En. de 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??

Respuestas (1)

NVSL
NVSL el 29 de En. de 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.

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by