How can I make this loop faster?
Show older comments
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
Answers (1)
Ameer Hamza
on 3 Apr 2020
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 Comments
Mohamad Al Hassan
on 3 Apr 2020
Ameer Hamza
on 3 Apr 2020
Edited: Ameer Hamza
on 3 Apr 2020
Does the code given in my answer work for your problem?
Mohamad Al Hassan
on 3 Apr 2020
Ameer Hamza
on 3 Apr 2020
Are you trying to implement the convolution function?
Mohamad Al Hassan
on 3 Apr 2020
Ameer Hamza
on 3 Apr 2020
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.
Categories
Find more on Programming in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!