필터 지우기
필터 지우기

another method to for loop

조회 수: 3 (최근 30일)
muhammad ismat
muhammad ismat 2015년 5월 27일
답변: Roger Stafford 2015년 5월 27일
how i can change for loop to code that is faster because i have a large dataset
for i=1:n,
for j=1:n,
if ind(i) == ind(j)
s(i,j)=abs(z(i,ind(i))-z(j,ind(j))) / (z(i,ind(i))+z(j,ind(j)))
else
s(i,j)=abs(z(i,ind(j))-z(j,ind(i))) / (z(i,ind(j))+z(j,ind(i)))
end
end
end
where n is the no of rows ind is the cluster number z is the distance from point to cluster no s is the similarity between any two point
  댓글 수: 1
per isakson
per isakson 2015년 5월 27일
편집: per isakson 2015년 5월 27일
What's ind and z?

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

답변 (1개)

Roger Stafford
Roger Stafford 2015년 5월 27일
There is one obvious way to speed things up. Your test for ind(i)==ind(j) is totally unnecessary and can be eliminated, because the expressions
abs(z(i,ind(i))-z(j,ind(j)))/(z(i,ind(i))+z(j,ind(j)))
and
abs(z(i,ind(j))-z(j,ind(i)))/(z(i,ind(j))+z(j,ind(i)))
are identically equal when ind(i) equals ind(j). Just write
for i=1:n
for j=1:n
s(i,j) = abs(z(i,ind(j))-z(j,ind(i)))/(z(i,ind(j))+z(j,ind(i)));
end
end
Even more important is that you should make sure the 's' matrix has been preallocated the proper amount of memory space before entering these for-loops. That make an enormous difference in speed. Doing an initial 'zeros' call with the appropriate dimensions would do the job.
I see a third way to possibly get more speed. You have symmetry in the placement of values in the 's' matrix, so you can cut the number of computations with 'z' by almost half.
for i = 1:n
for j = 1:i % <-- Note the 1:i instead of 1:n
s(i,j) = abs(z(i,ind(j))-z(j,ind(i)))/(z(i,ind(j))+z(j,ind(i)));
s(j,i) = s(i,j);
end
end

카테고리

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