Filter löschen
Filter löschen

For Loop inside another Loop

42 Ansichten (letzte 30 Tage)
heir ancestors
heir ancestors am 17 Mai 2017
Kommentiert: KALYAN ACHARJYA am 25 Mai 2017
I am trying to execute a code where I have to set two for loops. So here is the code
for j=1:b
for i=1:a
u=@(x) w/2.*cosd(ftilt(i)+(x))-(tand(GamasTday(j)).*(f-(w/2).*sind(ftilt(i)+(x))));
Bn(i,j)=fsolve(u,ftilt(1));
end
end
the problem is with the j , so here j iterating b and which is a 14 elements vector. what I want : take the first value of b for j==1 , do all the iterations for i iterating a which is 10 elements vector from 1 to a , solve and save results and then go back to j+1 , do all the iterations for i from 1 to a and go back again j+1............
the meaninig of the code is not important as the concept of the two loops , blocking the first loop at a value, go to the seconf loop execute all the iterations, go back to the firsst loop second value, go back to the inside loop all iterations .......etc
any ideas ?
thanks

Antworten (1)

Geoff Hayes
Geoff Hayes am 17 Mai 2017
If a and b are vectors/arrays and you want to iterate over each element of the array, then you would need to do something like
for j=1:length(b)
bVal = b(j);
for i=1:length(a)
aVal = a(j);
% do something
Bn(i,j)=fsolve(u,ftilt(1));
end
end
Note how we need to access an element of either array using i and j before we can start working with it.
  1 Kommentar
KALYAN ACHARJYA
KALYAN ACHARJYA am 25 Mai 2017
It seems OK, in your nesting loops code. As per the code j=1, then do the all iterations of i, when i iterations completed till a, then only j goes to j+1, i does all iterations for j+1...Do you face any problem in your code?

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by