Okay I have a 400000x2 matrix named A with data of velocity 2nd row versus time 1st row. Now each of these datas are a lot of 0's for the velocity and then suddenly there will be like 50 elements that are nonzero and this pattern continues. Now I want to define a function that can give me the first and last non-zero velocity in such a sequence. I've tried with the if-function but don't really know what to write. I wrote something like: for i=1:400000 if A(i,2)>0 A(i,2)=b end but first of all this would give me(if it worked) all the velocities in the sequence and I only want the 1st and last. Secondly I don't think you can use i as a variable in that sense..