Question

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.

Was it helpful?

Solution 2

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 

OTHER TIPS

This answer is generic for any chain size. It finds the longest chain in a vector x1 and retrieves the first element of that chain val.

First we'll use bwlabel to label connected components, For example:

s=bwlabel(x1);

Then we can use tabulate to get a frequency table of s, and find the first element of the biggest 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 you have one distinct maximal size chain. What happens for the case if you have more than one chain that has maximal lengths? (you can still use my code with slight modifications...)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top