How to group logical numbers in a vector?

1 回表示 (過去 30 日間)
Khaldon Qaid
Khaldon Qaid 2022 年 6 月 12 日
コメント済み: Khaldon Qaid 2022 年 6 月 13 日
I am trying to count how many groups of ones in a vector. Number 1 repeated three times in three positions in this vector.
Vector = [1 1 1 0 0 0 0 1 1 1 1 1 0 0 0 0 0 1 1 1 1 1 1];
The expected answer is
Num_gr_1 = 3
Could you help please?
  2 件のコメント
Jeffrey Clark
Jeffrey Clark 2022 年 6 月 12 日
@Khaldon Qaid, Num_gr_1 = sum(Vector>[Vector(2:end) 0]);
Khaldon Qaid
Khaldon Qaid 2022 年 6 月 13 日
Thank you for your help.

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

採用された回答

Matt J
Matt J 2022 年 6 月 12 日
編集済み: Matt J 2022 年 6 月 12 日
Use this:
Vector = logical( [1 1 1 0 0 0 0 1 1 1 1 1 0 0 0 0 0 1 1 1 1 1 1] );
Num_gr_1=max(groupTrue(Vector))
Num_gr_1 = 3
  1 件のコメント
Khaldon Qaid
Khaldon Qaid 2022 年 6 月 13 日
Thank you for your help.

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

その他の回答 (2 件)

dpb
dpb 2022 年 6 月 12 日
>> num_gr_1=sum(diff(Vector)==1)+(Vector(1)==1)
num_gr_1 =
3
>>
There are FEX submissions for runlength encoding that will give you all the details besides just the number of groups asked for here...if you want/need the locations of the groups,
>> gr_1=find([0 diff(Vector)]==1)
gr_1 =
1 8 18
>>
Above is specific for [0, 1]; the FEX submissions will find any/all runs. The above logic will deal with any specific values by converting the input vector to logical based on the looked-for value, but that's the limit to its flexibility.
But, it's quick/simple for the specific task.
  1 件のコメント
Khaldon Qaid
Khaldon Qaid 2022 年 6 月 13 日
Thank you for your help.

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


Image Analyst
Image Analyst 2022 年 6 月 12 日
If you have the Image Processing Toolbox you can label each group and count them in a single line of code with bwlabel :
Vector = [1 1 1 0 0 0 0 1 1 1 1 1 0 0 0 0 0 1 1 1 1 1 1]; % Sample data
[L, Num_gr_1] = bwlabel(Vector) % Label groups and count groups.
L = 1×23
1 1 1 0 0 0 0 2 2 2 2 2 0 0 0 0 0 3 3 3 3 3 3
Num_gr_1 = 3
  1 件のコメント
Khaldon Qaid
Khaldon Qaid 2022 年 6 月 13 日
Thank you for your help.

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

カテゴリ

Help Center および File ExchangeData Type Conversion についてさらに検索

製品


リリース

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by