Find consecutive nonzero values

I am trying to write a simple MATLAB program that will find the first chain (over 70) of consecutive nonzero values ​​and return the initial value of this sequential chain.

I work with movement data from the joystick, and there are several thousand rows of data with a mixture of zeros and non-zero values ​​before the start of the actual trial period (from subjects slightly moving the joystick to the start of the actual launch).

I need to get rid of these lines before I begin to analyze the movement from the tests.

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

EDIT: here is 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 that has a maximum chain of 72, but I don’t know how to find the maximum chain and return its first value, so I know where to crop. I also really don't think this is the best strategy since the maximum chain in my data will be tens of thousands of values.

+4
source share
2 answers

You do not need to use a helper vector to track 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 elements in a chain from x , you can simply:

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

EDIT (based on comment):
The reason you did this did not work, because you did not reset the counter when you ran into 0, which:

 else count = 0; 

- for; he resets the process if you want. For clarity, in your source code this will reflect on:

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

This answer is common to any chain size. It finds the longest chain in the vector x1 and extracts the first element of this chain val .

First we will use bwlabel to mark connected components, for example:

 s=bwlabel(x1); 

Then we can use tabulate to get the frequency table s and find the first element of the largest connected component:

 t=tabulate(s); [C,I]=max(t(:,2)); val=x1(find(s==t(I,1),1, 'first')); 

This should work for the case when you have one great max chain. What happens if you have more than one chain with a maximum length? (you can still use my code with slight modifications ...)

+2
source

Source: https://habr.com/ru/post/1488803/


All Articles