How can I quantify the number of cells between specific values?

I have a 100x1500 array [A] filled with zeros and ones.
For example, A(1,:) = 0 0 0 0 0 0 1 0 0 0 1 0 1 0 1 0 0 0 1....
For each row, I would like to find the average distance, or average number of zeros, between ones. Is there a simple way to do this?

3 件のコメント

the cyclist
the cyclist 2022 年 12 月 9 日
In a given row, do you want to ignore leading zeros and trailing zeros, or count them as part of the average?
For example, if
A = [0 0 0 1 0 1 0 0 1 0 0 0];
do you want the mean of [3 1 2 3], or just the mean of [1 2]?
omidm
omidm 2022 年 12 月 9 日
I'd like to ignore the leading and trailing zeros, so just the mean of [1 2] in your example. Thanks for clarifying.
Voss
Voss 2022 年 12 月 9 日
編集済み: Voss 2022 年 12 月 9 日
@omidm: How should consecutive ones be treated? That is, should they be considered as having a run of zero zeros in between them? Consider:
A = [1 0 1 1 0 0 0 1]
Is that a sequence of 1 zero followed by a sequence of 3 zeros (average length 2), or is it a sequence of 1 zero followed by a sequence of 0 zeros followed by a sequence of 3 zeros (average length 4/3)?

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

 採用された回答

Voss
Voss 2022 年 12 月 9 日
A = [0 0 1 0 0 0 0 1 1 0
1 0 1 0 0 0 1 1 0 0
0 1 1 1 0 0 1 0 1 0
1 0 0 0 1 1 1 0 1 0
1 1 1 0 1 0 0 0 0 1
1 0 0 1 1 1 1 1 1 0
0 0 1 0 1 0 0 0 0 0
1 1 1 1 0 1 0 1 0 1
0 0 0 0 1 1 0 1 0 1
0 1 0 1 0 1 1 1 1 0];
[r,c] = find(A);
groupsummary(c,r,@mean_diff)
ans = 10×1
4.0000 2.0000 1.5000 2.0000 2.5000 2.0000 1.0000 1.0000 1.0000 1.0000
function out = mean_diff(x)
m = diff(x)-1;
out = mean(m(m > 0));
end

1 件のコメント

omidm
omidm 2022 年 12 月 9 日
This worked great, thank you. Indeed I did not want consecutive ones to have a value of zero between them. Thanks again!

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

その他の回答 (1 件)

Eric Delgado
Eric Delgado 2022 年 12 月 9 日
I don't know if my solution is the "simple way" that you request! :)
randomMatrix = randi([0,1],10)
randomMatrix = 10×10
0 0 1 0 0 0 0 1 1 0 1 0 1 0 0 0 1 1 0 0 0 1 1 1 0 0 1 0 1 0 1 0 0 0 1 1 1 0 1 0 1 1 1 0 1 0 0 0 0 1 1 0 0 1 1 1 1 1 1 0 0 0 1 0 1 0 0 0 0 0 1 1 1 1 0 1 0 1 0 1 0 0 0 0 1 1 0 1 0 1 0 1 0 1 0 1 1 1 1 0
meanZeros = zeros(height(randomMatrix), 1);
for ii = 1:height(randomMatrix)
meanZeros(ii) = mean(diff(find(randomMatrix(ii,:) == 1))-1);
end
meanZeros
meanZeros = 10×1
2.0000 1.3333 0.7500 1.0000 1.2500 0.3333 1.0000 0.5000 0.6667 0.4000

1 件のコメント

Voss
Voss 2022 年 12 月 9 日
Note that this method treats consecutive 1's as containing zero 0's in between them, e.g., for the first row of A above, this method gives the average number of zeros as 2 = (4+0)/2 rather than 4 = 4/1.
It's not clear whether this is what OP intends.

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

カテゴリ

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

タグ

質問済み:

2022 年 12 月 9 日

コメント済み:

2022 年 12 月 9 日

Community Treasure Hunt

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

Start Hunting!

Translated by