How can i make comparison faster

3 ビュー (過去 30 日間)
Mats
Mats 2017 年 10 月 26 日
コメント済み: Andrei Bobrov 2017 年 10 月 26 日
My aim with the loop is to pick out all elements of C that are within range r of rd and range t of td (rd and td are range matrices). Then multiply the elements together and add them to a sum.
This loop is called about a million times and is relatively slow.
Does anyone have an idea of how I can increase the speed of the loop? (I have tried code generation which turned out slower, and parallelism)
for i = 1:indN
D = C(rd(ind(i),:)<r & td(ind(i),:)<t); % Check for <r and <t
if (isempty(D)) D=0; end
gSum = gSum + prod(D);
end
Profiling gives that D=C(.. line takes 84,7% of the entire run time (the other lines in the loop next to nothing)
  1 件のコメント
Jan
Jan 2017 年 10 月 26 日
Please provide some test data. Optimizing code depends on the inputs also. E.g. it matters, if there are repetitions in ind, or if C is a [1e7 x 1e2] or [1e2 x 1e7] matrix.

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

採用された回答

Jan
Jan 2017 年 10 月 26 日
index = (rd(ind, :) >= r | td(ind, :) >= t);
D = C;
D(index) = 1;
gSum = sum(prod(D, 2));
  1 件のコメント
Andrei Bobrov
Andrei Bobrov 2017 年 10 月 26 日
+1! Nice!
Small fixed:
D = ones(numel(ind),1)*C(:)';

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

その他の回答 (1 件)

Andrei Bobrov
Andrei Bobrov 2017 年 10 月 26 日
編集済み: Andrei Bobrov 2017 年 10 月 26 日
[ii,jj] = find(rd(ind,:) < r & td(ind,:) < t);
gSum = sum(accumarray(ii,C(jj),[],@(x)prod(x)));

カテゴリ

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

Community Treasure Hunt

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

Start Hunting!

Translated by