How can I write this to run more quickly, without a loop?
1 visualizzazione (ultimi 30 giorni)
Mostra commenti meno recenti
Daniel Drucker
il 17 Lug 2020
Commentato: Daniel Drucker
il 17 Lug 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 Commenti
Risposta accettata
Image Analyst
il 17 Lug 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, []);
Più risposte (0)
Vedere anche
Categorie
Scopri di più su Matrix Indexing in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!