for loop over subset - finding indices vs if-clause

4 ビュー (過去 30 日間)
Felix Müller
Felix Müller 2021 年 7 月 5 日
編集済み: Jan 2021 年 7 月 13 日
I want to compare two-cell arrays (X and Y) field by field (each field is a 2-dimensional array of points) and for each comparison compute how many points overlap. However I have a condition that needs to be fulfilled in each instance (which depends on some numbers in an array). Which of the following approaches makes more sense (speed or other issues)? Is there even a significant difference?
edit: The condition to check consists of two number comparisons, i.e. if/find array(jj)>= 0.5*K && array(jj)<=2*K, where K is constant for one ii.
1. find indices beforehand and run the second for-loop only over those
for ii=1:N
idx = find(jj that fulfill CONDITION in array);
for jj=idx
matrix(ii,jj) = sum(ismember(X{ii}, Y{jj}));
end
end
2. run for-loop over all indices and check condition individually with an if-clause
for ii=1:N
for jj=1:M
if Y(jj) fulfills CONDITION in array
matrix(ii,jj) = sum(ismember(X{ii}, Y{jj}));
end
end
end

採用された回答

Felix Müller
Felix Müller 2021 年 7 月 5 日
I ended up following Jan's advice and coded and timed it. It seems the first approach (finding indices and the running only over those) is slightly faster. It was between 0% and 5% less time used for the first approach compared to the second. I only tested for five random cases in my data.
If anybody has some insight into why this is faster, I'd be very interested to hear.
  8 件のコメント
Jan
Jan 2021 年 7 月 9 日
Maybe you want to post a minimal working example of the part, which consumes the most time of your code. Then we could check, if there are some other ways to speed this up. For 2D data there should be a fast approach using sortrows() and diff().
Felix Müller
Felix Müller 2021 年 7 月 13 日
編集済み: Jan 2021 年 7 月 13 日
I have posted a new question because this issue is independent from the one I asked about here. Link to the new question: https://de.mathworks.com/matlabcentral/answers/877513-speed-up-ismember-with-two-dim-data

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

その他の回答 (1 件)

Jan
Jan 2021 年 7 月 5 日
It depends. How expensive is "fulfill CONDITION"?
Simply try it. Implement both versions and measure the timings with tic/toc.
  1 件のコメント
Felix Müller
Felix Müller 2021 年 7 月 5 日
I'll update the question, but it's only two number comparisons (i.e. if array(jj)>= 0.5*K && array(jj)<= 2*K, where K is constant for one ii).

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

カテゴリ

Help Center および File ExchangeArgument Definitions についてさらに検索

製品


リリース

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by