Search code examples
matlabfindreturn-valuechain

find consecutive nonzero values


I am trying to write a simple MATLAB program that will find the first chain (more than 70) of consecutive nonzero values and return the starting value of that consecutive chain.

I am working with movement data from a joystick and there are a few thousand rows of data with a mix of zeros and nonzero values before the actual trial begins (coming from subjects slightly moving the joystick before the trial actually started).

I need to get rid of these rows before I can start analyzing the movement from the trials.

I am sure this is a relatively simple thing to do so I was hoping someone could offer insight. Thank you in advance

EDIT: Here's what I tried:

s = zeros(size(x1)); 

for i=2:length(x1) 
    if(x1(i-1) ~= 0) 
        s(i) = 1 + s(i-1); 
    end 
end 

display(S); 

for a vector x1 which has a max chain of 72 but I dont know how to find the max chain and return its first value, so I know where to trim. I also really don't think this is the best strategy, since the max chain in my data will be tens of thousands of values.


Solution

  • You don't need to use an auxiliary vector to keep track of the index:

    for i = 1:length(x)
        if x(i) ~= 0
                count = count + 1;
        elseif count >= 70
                lastIndex = i;
                break;
        else
                count = 0;
        end
    
        if count == 70
               index = i - 69;
        end
    end
    

    To remove all of the elements in the chain from x, you can simply do:

    x = x([lastIndex + 1:end]);
    

    EDIT (based off comment):
    The reason that the way you did it didn't work was because you didn't reset the counter when you ran into a 0, that's what the:

    else
       count = 0;
    

    is for; it resets the process, if you will. For some more clarity, in your original code, this would be reflected by:

      if x1(i-1) ~= 0 
            s(i) = 1 + s(i-1); 
      else
            s(i) = 0;
      end