How do I ignore the first few 0s in a vector but not ignore the 0s in the middle?

If i have the following vector: p = [0;0;0;0;1;2;5;4;6;0;0;0;6]
how would I code in such a way that I can ignore the first few zeros till a valid value (>0, in this case '1'). I don't want to remove/ignore the 0s in middle because I am going to be interpolating between the 2 valid values beside the 0s. so far, i have the following code:
p = [0;0;0;0;1;2;5;4;6;0;0;0;6]
for i = 1:13
if p(i) == 0
display('ignore')
else
currentValue = p(i)
if i ~= 1
prevValue = p(i-1)
if(i<8)
nextValue= p(i+1)
end
if (currentValue == 0 && prevValue ~= 0)
previousindex = i-1
speedUsed = prevValue
end
if currentValue == 0 %was nextValue == 0
counter = counter+1
i = i+1
end
if prevValue == 0 && currentValue == 0 && nextValue ~= 0
p([i+1-counter:i]) = interp(p(previousindex),nextValue,counter);
% i = i+1
end
end
end
end
but, obviously, every time p(i) = 0, it will ignore it....I'm sure I'm just missing something obvious but I really can't see it. I would appreciate any help!
Thank you

 Accepted Answer

To just drop the leading zeros, how about this?
p = p(find(p,1):end);
And is this what you're trying to achieve via the interpolation?
idx = 1:length(p);
newp = interp1(idx(p~=0), p(p~=0), idx);

2 Comments

Hi, thank you for the solution! however, is there anyway to do this without removing the 0s from a?
so if a = [0;0;0;0;1;2;5;4;6;7;0;0;0;2;5;0;2]
for i = 1:13 % go through a from a(1) till valid point. %start interpolation algorithm from valid point end
at the end of the for loop, a would still be a = [0;0;0;0;1;2;5;4;6;7;0;0;0;2;5;0;2]
thank you!
Yes:
saved_a = a;
% Now your loop, then
a = saved_a; % Restore a.

Sign in to comment.

More Answers (1)

Hint:
p1 = [0;0;0;0;1;2;5;4;6;0;0;0;6];
ixf = find( p1>0, 1, 'first' );
p2 = p1( ixf : end );
>> p2'
ans =
1 2 5 4 6 0 0 0 6

1 Comment

Hi, thank you for the solution! however, is there anyway to do this without removing the 0s from a?
so if a = [0;0;0;0;1;2;5;4;6;7;0;0;0;2;5;0;2]
for i = 1:13 % go through a from a(1) till valid point. %start interpolation algorithm from valid point end
at the end of the for loop, a would still be a = [0;0;0;0;1;2;5;4;6;7;0;0;0;2;5;0;2]
thank you!

Sign in to comment.

Categories

Find more on Interpolation in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!