How to automatically introduce a nested layer of for-loop?
Afficher commentaires plus anciens
Given a set of x-values
, I want to create a script that generates a product of n numbers.
, I want to create a script that generates a product of n numbers. For example, if I want to generate products of 2 numbers, i.e.
and so on, the script would be:
and so on, the script would be:for i_1=1:3
for i_2=1:3
Product=X(i_1)*X(i_2)
end
end
There will be 2 for-loops, one nested in another.
If I want to generate products of 3 numbers, i.e.
and so on, the script would be:
and so on, the script would be:for i_1=1:3
for i_2=1:3
for i_3=1:3
Product=X(i_1)*X(i_2)*X(i_3)
end
end
end
There will be 3 for-loops, i.e. 2 nested loops in an external loop.
Is there a way to automate this, like a recursion, so when n increases, it will automatically introduce a nested for-loop in the original script? The concept is like this:
n=n
for i_1=1:3
for i_2=1:3
for i_3=1:3
.
.
.
for i_n=1:3
Product=X(i_1)*X(i_2)*X(i_3)*...*X(i_n)
end
.
.
.
end
end
end
2 commentaires
Yasasvi Harish Kumar
le 26 Fév 2019
Modifié(e) : Yasasvi Harish Kumar
le 26 Fév 2019
The Product variable gets over written in each iteration. I dont see why you would have a loop for it.
If you still need to write multiple loops, try recursive function as a solution.
Réponse acceptée
Plus de réponses (0)
Catégories
En savoir plus sur Loops and Conditional Statements dans Centre d'aide et File Exchange
Produits
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!