Performance: for each element with value '1', find amount of elements with value '2' after it

1 回表示 (過去 30 日間)

Given an array (values are double precision), e.g.

a = [0 0 1 0 0 1 2 2 1 0 2]';

For each element with value '1', I would like to find the amount of elements with value '2' after. For the example given above, the output should look like this:

b = [3 3 1]';

Very importantly, this should be as fast as possible, since 'a' can easily exceed 20000 elements. I have two solutions, one of which uses arrayfun and is slow but uses little code (which is preferred as well), the second implementation makes use of loops and is nearly twice as fast.

rows1 = find(a == 1); 
rows2 = find(a == 2);
b = arrayfun(@(x) sum(b > x), a);

and the second implementation:

rows1 = find(a == 1); 
rows2 = find(a == 2);
b = zeros(size(rows1));
for row = 1:numel(rows1)
    sel = rows2 > rows1(row);
    first2 = find(sel, 1, 'first');
    sumVal = numel(rows2) - first2 + 1;
    b(row) = sumVal;
end

I am aware that I can compress example #2 for less code. I wonder: is there a more performant implementation? Profiling the second solution shows me, that most time is lost for the combination of 'find' and 'sel = ...'.

採用された回答

Bruno Luong
Bruno Luong 2018 年 10 月 1 日
編集済み: Bruno Luong 2018 年 10 月 1 日
a = [0 0 1 0 0 1 2 2 1 0 2]
fa = flip(a);
c = cumsum(fa==2);
b = flip(c(fa==1))

b =

     3     3     1

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeMatrices and Arrays についてさらに検索

製品


リリース

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by