How do I find non-consecutive zero entries?

I am trying to obtain logical output by finding the entries which are 0 but with a condition that its previous entry must not be zero. I'd like to avoid using FOR loop since the size of the input matrix is quite large. But I just couldn't figure out how to avoid using FOR loop.
Here is the example of my input and desired output.
input = [6 6 5 3 0 0 2 0 3 1 0 0 0 4 0;
3 5 1 4 2 0 0 0 9 0 8 7 0 0 2]
output = [0 0 0 0 1 0 0 1 0 0 1 0 0 0 1;
0 0 0 0 0 1 0 0 0 1 0 0 1 0 0]
Any suggestions would be really appreciated.

 採用された回答

Walter Roberson
Walter Roberson 2011 年 3 月 11 日

0 投票

What if the first entry is 0? There is no entry before that, so is the non-existent entry non-zero or not?
[false(size(input,1),1) ~input(:,2:end) & input(:,1:end-1)]

その他の回答 (3 件)

Paulo Silva
Paulo Silva 2011 年 3 月 11 日

1 投票

Here's my messy code, Walter's solution is better and I also had the first value problem, I ignored the first value.
input=[input(1,:) input(2,:)]; %make a vector from the array
a=diff(input==0); %find the zeros
b=[0 a==1]; %insert the first value 0 and the result
output=[b(1:15);b(16:30)] %make the output an array
Peerapat V.Chareon
Peerapat V.Chareon 2011 年 3 月 11 日

0 投票

Thanks very much Walter and Paulo, the first value is always non-zero. Your codes work very well.
Sean de Wolski
Sean de Wolski 2011 年 3 月 11 日

0 投票

And another:
%Don't overwrite input because it's a built-in function!
%renamed input to x
output = (x==0&diff([zeros(size(x,1),1) x],[],2))

カテゴリ

ヘルプ センター および File ExchangeEntering Commands についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by