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!