count a vector with continuous non zero elements

3 ビュー (過去 30 日間)
Sam
Sam 2014 年 5 月 16 日
編集済み: the cyclist 2014 年 5 月 16 日
Is there a way to count non-zero elements in vector x below x=[0 1 1 1 0 0 1 1 1 1 1 0 0 0 0 1 1 1 1 1 1 1 0 1]
so that the output y will be y=[3 5 7 1]

回答 (2 件)

Azzi Abdelmalek
Azzi Abdelmalek 2014 年 5 月 16 日
x=[0 1 1 1 0 0 1 1 1 1 1 0 0 0 0 1 1 1 1 1 1 1 0 1]
ii=strfind([0 x 0],[0 1])
jj=strfind([0 x 0],[1 0])
out=jj-ii
  2 件のコメント
Sam
Sam 2014 年 5 月 16 日
thanks Azzi, can you explain to me what is this doing?
Azzi Abdelmalek
Azzi Abdelmalek 2014 年 5 月 16 日
ii=strfind([0 x 0],[0 1]) % find the indices corresponding to the switch from 0 to 1

サインインしてコメントする。


the cyclist
the cyclist 2014 年 5 月 16 日
編集済み: the cyclist 2014 年 5 月 16 日
Here's a similar approach:
y = diff(find([0 x 0]==0))-1;
y(y==0) = []
The first line identifies the zero locations, and then the "distance" between them. This distance is the length of the string of ones.
The second line removes the instances where that distance is zero (i.e. no 1's), since you are not interested in those.
Note that the reason you need to do this operation on "[0 x 0]" instead of just x is to be able to identify a string of ones at the beginning and end.

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by