Count instances of subarray inside array

6 ビュー (過去 30 日間)
Mitsu
Mitsu 2021 年 11 月 4 日
編集済み: Turlough Hughes 2021 年 11 月 7 日
For an array
A = [2,2,2,2];
I would like to count how many times [2,2] appears in A, using each value only in one possible pair.
For example,
numel(strfind(A,[2,2]))
returns 3.
But if each "2" is used only once, then we have only 2 instances, instead of 3.
A is not necessarily of all same elements or even-number size, it could be e.g. A = [1,2,3].
Is there a simple way to do that?
  2 件のコメント
KSSV
KSSV 2021 年 11 月 4 日
Try reshape into n*2 array and use ismember with rows option.
Mitsu
Mitsu 2021 年 11 月 4 日
I mean for this approach to work regardless of the size and elements, such as A = [1,2,3]. I edited the question to clarify.

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

回答 (1 件)

Turlough Hughes
Turlough Hughes 2021 年 11 月 4 日
You could do the following:
b = A == 2; % binary indicating where A equal to 2
count = 0;
ii = 1;
while ii < numel(A)
if b(ii+1) && b(ii)
count = count + 1;
ii = ii + 1;
end
ii = ii + 1;
end
When there is a match, the loop variable, ii, increments an extra time so that each "2" is only used once.
  3 件のコメント
Mitsu
Mitsu 2021 年 11 月 4 日
編集済み: Mitsu 2021 年 11 月 4 日
Thank you. There might be no other way around but to do it following the logic in your answer. For now I will wait to see if there are other answers with simpler, maybe one-line, approach.
Turlough Hughes
Turlough Hughes 2021 年 11 月 4 日
編集済み: Turlough Hughes 2021 年 11 月 7 日
Another way would be to get the length of each group of twos (based on this answer by @Image Analyst) and then round down each group's length to the nearest whole number divisible by two:
measurements = regionprops(A == 2, 'Area');
allLengths = [measurements.Area];
count = sum(floor(allLengths/2))
(if you have the image processing toolbox)

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

カテゴリ

Help Center および File ExchangeMatrices and Arrays についてさらに検索

タグ

製品


リリース

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by