Clear Filters
Clear Filters

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

2 views (last 30 days)

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 = ...'.

Accepted Answer

Bruno Luong
Bruno Luong on 1 Oct 2018
Edited: Bruno Luong on 1 Oct 2018
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

More Answers (0)

Categories

Find more on Startup and Shutdown in Help Center and File Exchange

Products


Release

R2018a

Community Treasure Hunt

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

Start Hunting!