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, []);
  1 件のコメント
Daniel Drucker
Daniel Drucker 2020 年 7 月 17 日
Thanks, that definitely helps.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

タグ

製品


リリース

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by