How can I make this loop faster?
이전 댓글 표시
Why is this simple loop taking me so much time?
n=2^13;
idx=cell(2*n-1,1);
for i=1:2*n-1
temp=zeros(i,2);
for j=1:i
if j>n
idx1=0;
else
idx1=j;
end
if i-j+1>n
idx2=0;
else
idx2=i-j+1;
end
temp(j,:)=[idx1,idx2];
end
idx{i}=temp;
end
답변 (1개)
Ameer Hamza
2020년 4월 3일
The matrices generated by your code just contain a linear array of integers. If you can tell, why do you want to create them in the first place, maybe I can suggest a better solution. Anyway, for the current code, try the following
n=2^13;
idxA=cell(2*n-1,1);
for i=1:2*n-1
if i <= n
temp = (1:i)';
else
temp = [(1:n)';zeros(i-n,1)];
end
idxA{i} = [temp flipud(temp)];
end
On my system, the execution time improved by about 8x.
tic
n=2^13;
idxA=cell(2*n-1,1);
for i=1:2*n-1
if i <= n
temp = (1:i)';
else
temp = [(1:n)';zeros(i-n,1)];
end
idxA{i} = [temp flipud(temp)];
end
toc
tic
n=2^13;
idxB=cell(2*n-1,1);
for i=1:2*n-1
temp=zeros(i,2);
for j=1:i
if j>n
idx1=0;
else
idx1=j;
end
if i-j+1>n
idx2=0;
else
idx2=i-j+1;
end
temp(j,:)=[idx1,idx2];
end
idxB{i}=temp;
end
toc
isequal(idxA, idxB)
Result:
Elapsed time is 1.842785 seconds.
Elapsed time is 15.006841 seconds.
ans =
logical
1
댓글 수: 6
Mohamad Al Hassan
2020년 4월 3일
Ameer Hamza
2020년 4월 3일
편집: Ameer Hamza
2020년 4월 3일
Does the code given in my answer work for your problem?
Mohamad Al Hassan
2020년 4월 3일
Ameer Hamza
2020년 4월 3일
Are you trying to implement the convolution function?
Mohamad Al Hassan
2020년 4월 3일
Ameer Hamza
2020년 4월 3일
Sorry, I don't understand this code, so it is difficult for me to suggest an optimization by vectorizing. This code runs quite slow, and maybe you need to rethink about your problem from basics. There might be some other efficient way to get the system of equations you want.
카테고리
도움말 센터 및 File Exchange에서 Programming에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!