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

1 visualización (últimos 30 días)

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

Respuesta aceptada

Bruno Luong
Bruno Luong el 1 de Oct. de 2018
Editada: Bruno Luong el 1 de Oct. de 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

Más respuestas (0)

Categorías

Más información sobre Matrices and Arrays en Help Center y File Exchange.

Productos


Versión

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by