MATLAB: Deleting runs of zeros

deleting observationsdeleting runs of zeros

Hello! I have a dataset that occasionally has runs of zeros. I would like to delete those runs from my data. How do I state that for any run of 3 or more zeros in my data, I would like Matlab to completely delete those observations from my dataset.
So for example, I have a dataset that looks like
[1 5;2 7;3 0;4 0;5 0;6 3]
I would like the that run of zeros deleted so that my new dataset looks like…
[1 5;2 7;6 3]
Any help is greatly appreciated!!

Best Answer

  • one possible way, use strfind (which works with numbers despite the name). Using a more complex example (to show that it works regardless of the numbers of 0 in the run):
    data = [1 5; 2 0; 3 0; 4 2; 5 3; 6 0; 7 0; 8 0; 9 0; 10 1; 11 0; 12 0; 13 0]
    startseq = strfind(data(:, 2)', [0 0 0]);
    toremove = unique([startseq, startseq+1, startseq+2]);
    data(toremove, :) = []