How can I write this to run more quickly, without a loop?

2 visualizaciones (últimos 30 días)
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

Respuesta aceptada

Image Analyst
Image Analyst el 17 de Jul. de 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, []);

Más respuestas (0)

Categorías

Más información sobre Matrix Indexing en Help Center y File Exchange.

Etiquetas

Productos


Versión

R2019b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by