How can I write this to run more quickly, without a loop?
1 view (last 30 days)
Show older comments
Daniel Drucker
on 17 Jul 2020
Commented: Daniel Drucker
on 17 Jul 2020
What would be the proper Matlab-y way to write this? It's a bottleneck in my code.
% IDX_full is a n_items x 1 double
M = zeros(n_items,n_items);
for i = 1:length(IDX_full)
for j = 1:length(IDX_full)
if (IDX_full(i) == IDX_full(j)) && (IDX_full(i) > 0)
M(i,j) = 1;
end
end
end
0 Comments
Accepted Answer
Image Analyst
on 17 Jul 2020
How big is your array? I tried 10 thousand by 10 thousand, and got it down from 1.05 seconds to 0.67 seconds with this vectorization:
% IDX_full is a n_items x 1 double
n_items = 10000;
IDX_full = randi([0, 2], n_items, 1);
M = zeros(n_items,n_items);
tic
for i = 1:length(IDX_full)
if IDX_full(i) > 0
indexes = IDX_full(i) == IDX_full;
M(i, indexes) = 1;
end
end
toc
% M
% imshow(M, []);
More Answers (0)
See Also
Categories
Find more on Matrix Indexing 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!