Count the sequence of same values in an array until an new value comes up

7 ビュー (過去 30 日間)
J.P.
J.P. 2016 年 12 月 17 日
コメント済み: Image Analyst 2022 年 12 月 1 日
Hello everybody!
I need to count every sequence of same values, until a new, different sequence of a value comes up. Then, I need to count the new sequence.
As example: My row is 00000001111-1-1-1-1-1000111
I want to get a table saying:
Element: 0 1 -1 Count: 2 2 1
This means that I have 2 sequences of zeros, two sequences of ones and one sequence of minus ones.
I don't need to count each value, just the sequence until the next sequnece of values!
Thank you.
  1 件のコメント
dpb
dpb 2016 年 12 月 17 日
Bruno Luong has a runs-counting submittal at FileExchange that'll probably be just the ticket...

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

回答 (3 件)

the cyclist
the cyclist 2016 年 12 月 17 日
編集済み: the cyclist 2016 年 12 月 17 日
Get RunLength from the File Exchange.
Then,
x = RunLength([0 0 0 1 1 -1 -1 0 0 1 1 ]);
u = unique(x); % The unique values
c = histcounts(x,[u Inf]); The number of sequences of those unique values

Jan
Jan 2016 年 12 月 18 日
編集済み: Jan 2016 年 12 月 18 日
Simpler than RunLength, because the sequence length does not matter:
x = [0 0 0 1 1 -1 -1 0 0 1 1 ];
B = x([diff(x)~=0, true]);
u = unique(B); % The unique values
c = histcounts(x, [u, Inf]);
The calculation of B is slower then with RunLength.mex, but if runtime is not the problem in your case, you can save the time and effort for compiling.
  3 件のコメント
Reji G
Reji G 2022 年 12 月 1 日
How to count number of zeros(or any other particular number) alone?
Image Analyst
Image Analyst 2022 年 12 月 1 日
@Reji G here are some ways
x = [0 0 0 1 1 -1 -1 0 0 1 1 ];
numZeros = nnz(x == 0)
numZeros = 5
numZeros = numel(x) - nnz(x)
numZeros = 5
numZeros = sum(x == 0, 'all')
numZeros = 5

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


Image Analyst
Image Analyst 2016 年 12 月 18 日
This is trivial (4 lines of code) with bwlabel of the Image Processing Toolbox which counts regions:
m = [0 0 0 0 0 0 0 1 1 1 1 -1 -1 -1 -1 -1 0 0 0 1 1 1] % Instantiate sample data.
uniquem = unique(m)
for k = 1 : length(uniquem)
[labeledData, counts(k)] = bwlabel(m == uniquem(k));
end
% Done! Now show to command window so we can see the results.
counts % Shows 1,2,2 for number of regions for -1, 0, 1
If you don't want the counts in numerical order like -1,0,1 then you can of course simply put "counts" in whatever order you want to sort it in.
  1 件のコメント
J.P.
J.P. 2016 年 12 月 18 日
Trivial for you!
Thank you so much! Again all of you. I have got one more point...

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

カテゴリ

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

Community Treasure Hunt

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

Start Hunting!

Translated by