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 CenterFile Exchange 中查找有关 Matrices and Arrays 的更多信息

产品


版本

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by