speed up for loops
조회 수: 1 (최근 30일)
이전 댓글 표시
how can I speed up these for loops? it seems to run forever! shrtPth is an array which contains shortest path of two nodes. i.e. this code is a kind of Floyd algorithm for nodes with two indices, such as: E(:,ii,i) & E(:,jj,j).
for m=1:N
for n=1:blk
for i=1:N
for ii=1:blk
for j=1:N
for jj=1:blk
shrtPth(i,ii,j,jj)=min(shrtPth(i,ii,j,jj),shrtPth(i,ii,m,n)+shrtPth(m,n,j,jj));
end
end
end
end
end
end
thanks by advance...
댓글 수: 0
답변 (2개)
Matt J
2013년 12월 20일
편집: Matt J
2013년 12월 20일
There doesn't seem to be a good reason to have two indices per node. You can equally well index them with one index and then you will have fewer for-loops, which should be faster.
However, before you reinvent the wheel, you should know that there are many shortest path routines on the File Exchange,
댓글 수: 3
Matt J
2013년 12월 20일
Using SUB2IND, you can convert multi-dimensional indices to one-dimensional linear indices.
Image Analyst
2013년 12월 20일
Reverse the order of the indexes. You're doing it the exact opposite way you should be doing it. You're doing it the slowest way possible. MATLAB goes down the rows (left most index) before it does the others. Look, try this code:
n=300;
m = rand(n,n,n);
tic;
for i1 = 1 : n
for i2 = 1 : n
for i3 = 1 : n
m(i1,i2,i3) = m(i1,i2,i3)+1;
end
end
end
toc;
tic;
for i3 = 1 : n
for i2 = 1 : n
for i1 = 1 : n
m(i1,i2,i3) = m(i1,i2,i3)+1;
end
end
end
toc;
In the command window, notice almost a 4x speedup:
Elapsed time is 0.911281 seconds.
Elapsed time is 0.246471 seconds.
댓글 수: 2
Image Analyst
2013년 12월 21일
The sizes don't matter. I could have made different sizes and the results would be the same. It was faster to create the code with the same size so that's why I did it. I hope it didn't confuse you. If the total number of iterations on the inner most loop is not more than a million or so, then you might not notice any difference in time.
참고 항목
카테고리
Help Center 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!