repeating for loop under another for loop

2 visualizzazioni (ultimi 30 giorni)
haejun
haejun il 3 Lug 2013
Hello,
I have 100 varibles which is organized in a hierarchical way. Some of them have only 3 different values (for example, 0.1,0.5 and 1.0) and others are calculated based on those values. a1 = 0.1, a2 = 0.5, a3 = 0.1 a4 = 0.2*a1 + 0.5*a2 + 0.3*a3 , a5 = 0.5, a6 = 0.1, a7 = 0.2*a1 + 0.3*a4+ 0.4*a5 + 0.7*a6, a8 =0.3, a9 = 0.8*a7+0.2*a8, .... a100 = 0.1*a3+ 0.2*a89 + 0.1*a9 + 0.6*a99
The number of variable is about 100. What I am trying to do is to check all possible values (for those variables(selective varibles) having only three possible values of 0.1, 0.5, 1.0) and to find proper combination of variable value set. For example, I am looking for all combination of seletive variables(a1,a2, a3, a5, a6....) to satisfy a100 > 0.5.
what I first thought is setting up almost 100 times of for-loop. assuming 90 selective variables and 10 variables determined based on equations, A = [0.1, 0.5, 1.0];
for i99=1:3
a99 = A(i99);
for i97=1:3
a97 = A(i97)
......
for i5=1:3
a5 = A(i5)
for i3=1:3
a3 = A(i3)
for i2=1:3
a2 = A(i2)
for i1=1:3
a1 = A(a1)(i1)
end
end
end
a4 = 0.2*a1 + 0.5*a2 + 0.3*a3,
end
end end end end end.....
a100 = 0.1*a99 + 0.2*a98 +0.7*a95 + 0.7*a40;
if a100>0.5
agoodcombinatin = (a1, a2, a3, a5, .... a97,a99)
end
end
But this is too tedious and there should be a better way to do this in matlab. I hope you can help me solve this in a better way.
Thank you.

Risposte (1)

Guru
Guru il 4 Lug 2013
When looking at nested for loops like yours, the first question I always ask is why are you using a for loop to begin with? To address this question, we can look at some of your innermost for loops:
for i3=1:3
a3 = A(i3)
for i2=1:3
a2 = A(i2)
for i1=1:3
a1 = A(a1)(i1)
end
end
end
Now we can step through this in our heads and realize the following: 1) a3 is not used in a2 or a1. a2 is not used in a1 2) A little closer inspection will tell us because of this independence in their relationship, not only are the for loops unnecessary, they are in fact pointless
The following code will produce the same results as this innermost nested for loop structure:
a3 = A(3);
a2 = A(3);
a1 would simply give you an error as you are trying to say that
a1 = A(a1)(3)
which does not make sense in MATLAB.

Categorie

Scopri di più su Symbolic Math Toolbox in Help Center e File Exchange

Prodotti

Community Treasure Hunt

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

Start Hunting!

Translated by