Find contiguous values in vector that sum to specified value
Mostrar comentarios más antiguos
Hi all,
I have a column vector e.g. V=[1 0 2 2 1 1]
I need to look within this vector and find a run of contiguous values which sum to a specific value (e.g. 5). If such a value can be found, I want the code to simply return the number of contiguous values it needed to add up to reach that target value.
So in the example above, I can see that I can add [1 0 2 2] to get 5, so that's 4 contiguous values summed, I can also see I can get 5 by adding [2 2 1] (3 values summed).
One way of doing this is applying a moving window which goes through the data summing the contents of the window. Every time the sum of the window equals my target value, that counts as a hit. The window then increases in size (1:length(V)).
The big problem I can see with this is computationally this is likely to be painfully slow because my length(V)=10^6. It's a million window sizes, and up to a million window shifts for each window
I wondered if anyone out there can think of a better way of achieving my aim?
1 comentario
Roger Stafford
el 21 de En. de 2013
I have two questions to ask which are important in choosing an efficient algorithm. 1) Are all your V values integers as in your example or is there a concern with round-off errors in checking sums? 2) Are all the values non-negative?
Respuesta aceptada
Más respuestas (1)
Another approach might be to apply the IPDM tool
to the vector
Vc=cumsum(V(:));
Basically, every difference
Vc(i)-Vc(j)
corresponds to a sum over a particular window. The IPDM tool will compute these differences, but gives various options to restrict the search efficiently to certain component differences of interest. In your case, you might use
out = ipdm(Vc,'Subset','Maximum',...
'Limit',targetvalue+tolerance,...
'Result','Structure');
idx= (out.distance <= targetvalue-tolerance )&...
(out.rowindex > out.columnindex);
out.rowindex(idx)=[];
out.columnindex(idx)=[];
WindowWidths = out.columnindex-out.rowindex+1;
Categorías
Más información sobre Dimensionality Reduction and Feature Extraction en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!