Infinite nested loop in matlab

8 次查看(过去 30 天)
elham eftekhari
elham eftekhari 2020-1-27
回答: NVSL 2025-1-29
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 个)

NVSL
NVSL 2025-1-29
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.

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by