필터 지우기
필터 지우기

Reducing the number of for loops

조회 수: 1 (최근 30일)
Muhannad
Muhannad 2015년 11월 19일
댓글: Walter Roberson 2015년 11월 20일
How can I reduce the number of for loops in the code below:
l = find(lamda >= fmin & lamda <= fmax);
lam = lamda(l);
n = length(lam);
C = zeros(n,n,n,n);
for i = 1:n
for ii = 1:n
for iii = 1:n
for iv = 1:n
A = [data(l(i),1) data(l(i),2) data(l(i),3);data(l(ii),1) data(l(ii),2) data(l(ii),3); data(l(iii),1) data(l(iii),2) data(l(iii),3); data(l(iv),1) data(l(iv),2) data(l(iv),3)];
C(i,ii,iii,iv) = cond(A);
end
end
end
C(i,i,i,i) = mean2(C);
i
end

채택된 답변

Walter Roberson
Walter Roberson 2015년 11월 20일
편집: Walter Roberson 2015년 11월 20일
A = data(l([i ii iii iv]), 1:3);
Other than that minor change, I think the best you will be able to do is hide a couple of loops using arrayfun() or pagefun(), and doing so will not necessarily improve performance. If you have the Parallel Processing Toolkit you might be able to work with a gpu array, possibly. And certainly you could run different combinations of the values in parallel.
  댓글 수: 2
Muhannad
Muhannad 2015년 11월 20일
Is it possible to reduce the number of for loops used in this code? as I think this will dramatically increase the speed.
Also can you give me an example for arrayfun() or pagefun() related to my code?
Walter Roberson
Walter Roberson 2015년 11월 20일
arrayfun() is internally implemented with loops, and requires function calls, so it can be slower than plain loops.
l = find(lamda >= fmin & lamda <= fmax);
lam = lamda(l);
n = length(lam);
C = zeros(n,n,n,n);
for i = 1:n
A1 = data(l(i),:);
for ii = 1:n
A2 = [A1; data(l(ii),:)];
for iii = 1:n
A3 = [A2; data(l(iii),:)];
C(i,ii,iii,:) = arrayfun(@(iv) cond([A3;data(l(iv),:)]), 1:n);
end
end
C(i,i,i,i) = mean2(C);
end
Your mean2(C) looks wrong. C has not been fully initialized yet because it has not had anything for large i put in yet. Are you counting on the fact that those values will be 0, and yet you are including the number of those 0s in the mean2 calculation? And do you really want the value to depend upon the order you fill C?

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Programming에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by