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!