For Loop inside another Loop

42 次查看(过去 30 天)
heir ancestors
heir ancestors 2017-5-17
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

回答(1 个)

Geoff Hayes
Geoff Hayes 2017-5-17
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 个评论
KALYAN ACHARJYA
KALYAN ACHARJYA 2017-5-25
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?

请先登录,再进行评论。

类别

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