Effacer les filtres
Effacer les filtres

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

2 vues (au cours des 30 derniers jours)

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

Réponse acceptée

Bruno Luong
Bruno Luong le 1 Oct 2018
Modifié(e) : Bruno Luong le 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

Plus de réponses (0)

Catégories

En savoir plus sur Startup and Shutdown dans Help Center et File Exchange

Produits


Version

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by