Improve the code's time of execution. I want to avoid the for loops and use element by element calculations. Do you guys have something in mind?? Thank you in advance.
2 views (last 30 days)
Show older comments
for i=1:v
for j=1:v
for k=1:m
if dm==k && j<=n && A~=j
ddii=((design(i,k)-design(j,k))^2);
summ=summ+ddii;
elseif dm~=k && j<=n && A~=j
ddii=((design(A,k)-design(j,k))^2);
summ=summ+ddii;
end
k=k+1;j=j;i=i;
end
ddcc(j,i,:)=[j i summ];
j=j+1; i=i; k=1;summ=0;
end
cc(i,:)=min(nonzeros(ddcc(:,i,3)));
i=i+1;j=1;k=1;
end
4 Comments
Accepted Answer
dpb
on 8 May 2016
See if the following produces correct output, first; should reduce the time slightly by eliminating redundant tests and shortening the loop on j. Whether it's significant will depend how many cases get missed so is data-dependent.
for i=1:v
for j=1:n
if j==A, continue, end
for k=1:n
if k==dm
ddii=((design(i,k)-design(j,k))^2);
summ=summ+ddii;
else
ddii=((design(A,k)-design(j,k))^2);
summ=summ+ddii;
end
end
ddcc(j,i,:)=[j i summ];
summ=0;
end
cc(i,:)=min(nonzeros(ddcc(:,i,3)));
end
After that, you're walking thru the arrays in the opposite storage as to sequential addressing; whether this is a major issue has to do with stride and cache size, etc., but might try using
design=design.';
before beginning the loop and see if it makes any difference in speed when the first index gets incremented sequentially in the innermost loop.
After that, I'd have to think more than I wish to expend on a Sunday afternoon to see if could do better on the actual computation altho it would seem with some consideration a logical addressing expression and pdist|pdist2 should be able to help.
3 Comments
dpb
on 8 May 2016
...
for k=1:n
if k==dm
ddii=((design(i,k)-design(j,k))^2);
...
Note that k in both references in the array is the column index and is the innermost loop. This means the stride between every access is size(design,1), not sequential if were design(k,i) instead. I had a brain cramp on the transpose operator by itself, though, you would need to reference the indices in the opposite order as well, and if the array isn't square as I figured was, then you have to rearrange the loop limits as well. But, the big idea is that should iterate over the leftmost array index first to process the array in sequential order.
Still think you should be able to do something with the pdistX functions and logical addressing, though...
More Answers (0)
See Also
Categories
Find more on Matrices and Arrays 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!