which for loop will completed first ??

조회 수: 1 (최근 30일)
Anil Kumar
Anil Kumar 2018년 12월 9일
댓글: Stephen23 2018년 12월 9일
for i=1:5
for j=1:4
v(i,j)=w*v(i,j)+c1*rand()*(pbest(i,j)-x(i,j))+c2*rand()*(gbest(1,j)-x(i,j));
end
end
how this loops will work.
thanks in advance
  댓글 수: 2
madhan ravi
madhan ravi 2018년 12월 9일
a=rand(3);
m=size(a,1);
n=size(a,2);
b=zeros(size(a,1),size(a,2));
for i=1:m
for j=1:n
b(i,j)=a(i,j) % this will make you understand the working of nested for loops
end
end
Stephen23
Stephen23 2018년 12월 9일
"which for loop will completed first ??"
Of any nested loops, the innermost one will finish first.

댓글을 달려면 로그인하십시오.

답변 (1개)

Image Analyst
Image Analyst 2018년 12월 9일
The inner j loop will finish first, for any given i. The j loop will execute its 4 iterations 5 times - one iteration of 4 times for every one of the 5 i values.
If the loops got very large (tens of thousands of iterations), you might notice a speed up if you switched the i and j loop because MATLAB is "column major" so it goes down rows (left most index) first before jumping over to the next column. So it would be faster if the inner most loop variable were the left most index.

카테고리

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