Turning 1s to 0s in a logical vector when element distance between 1s is below threshold
4 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Len Jacob
el 3 de Ag. de 2021
Comentada: Jonas
el 4 de Ag. de 2021
Hello,
I have a logical vector of 1.5 million elements. I need to look through the elements in the vector, and whenever I find a 1, I need to turn any potential subsequent 1s in the next N elements into 0s. While this would be easy to implement with a for loop, I'm struggling to figure out a more efficient way to do it.
Example:
If [ 1 1 0 0 0 0 1 0 1 0 0 0 1 ] is my vector, and my N threshold is 5, I want to turn that vector into [ 1 0 0 0 0 0 1 0 0 0 0 0 1 ].
Thank you in advance.
2 comentarios
Chien-Han Su
el 3 de Ag. de 2021
How about using find() to get indices of all trues, get distance from those indices by subtraction and turn true to false for those distance bellow threshold?
Respuesta aceptada
Jonas
el 4 de Ag. de 2021
you can try the follwing, but i don't know if it is faster
H = [ 1 1 0 0 0 0 1 0 1 0 0 0 1 ]; eraseNAfter=5; Hstr=num2str(H); out=regexprep(Hstr,['1' repmat('.',[1 3*eraseNAfter])],['1' repmat(' 0',[1 eraseNAfter])]); asDouble=str2mat(out)
i am also sure the regexp could be written nicer
2 comentarios
Jonas
el 4 de Ag. de 2021
that's true, fast solition would be padding the array and removing the padded elements at the end
H = [ 1 1 0 0 0 0 1 0 1 0 0 0 1 1]; eraseNAfter=5; H=[H repmat(0,[1 eraseNAfter])]; Hstr=num2str(H); out=regexprep(Hstr,['1' repmat('.',[1 3*eraseNAfter])],['1' repmat(' 0',[1 eraseNAfter])]); asDouble=str2mat(out); asDouble((end-eraseNAfter+1):end)=[]
Más respuestas (0)
Ver también
Categorías
Más información sobre Matrix Indexing en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!