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

조회 수: 1 (최근 30일)
Daniel Drucker
Daniel Drucker 2020년 7월 17일
댓글: Daniel Drucker 2020년 7월 17일
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

채택된 답변

Image Analyst
Image Analyst 2020년 7월 17일
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, []);

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

태그

제품


릴리스

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by