How to obtain repetition patterns (start, end indices) in an array?

4 ビュー (過去 30 日間)
Chaitanya P
Chaitanya P 2015 年 4 月 2 日
回答済み: Chaitanya P 2015 年 4 月 2 日
Hi,
My question is as follows:
Given an array N (see below) and a key value, I would like to identify the start and end indices of the pattern associated with the key.
N = [1 1 2 2 2 2 3 3 3 4 4 4 4 1 1 1 1 2 2 2 3 3 3 3 3];
key = 2;
For example, in the above, the pattern associated with '2' can be captured by a sequence of start indices and end indices. Thus, I would like the output:
start_indices = [3 18]
end_indices = [6 20]
How can I do this in MATLAB? Any help appreciated. Thanks in advance!
PS. The broader pattern in this problem is always cyclical. For example, a sequence of 1's is always followed by sequence of 2's, followed by sequence of 3's, followed by sequence of 4's and then back to a sequence of 1's.

採用された回答

Chaitanya P
Chaitanya P 2015 年 4 月 2 日
I found a simple way out, thanks for the response @Philipp - since this is a part of a big code I tried to keep away from looping.
key_inds = find(N==key);
start_index = key_inds(1);
end_index = key_inds(end);
start_indices = [start_index key_inds(find(diff(key_inds)>1)+1)];
end_indices = [key_inds(find(diff(key_inds)>1)) end_index];

その他の回答 (1 件)

Philipp Maier
Philipp Maier 2015 年 4 月 2 日
編集済み: Philipp Maier 2015 年 4 月 2 日
Please feel free to simplify the following:
flag = 1;
start_indices = [];
end_indices = [];
for i=1:numel(N)
if ((N(i)==key) && flag == 1)
start_indices = [start_indices i];
flag = 0;
elseif (flag == 0 && (N(i)~=key) )
end_indices = [end_indices i-1];
flag = 1;
end
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