find array dispersed within another array

1 回表示 (過去 30 日間)
Dan Klisiewicz
Dan Klisiewicz 2021 年 3 月 15 日
say I have two arrays:
A = [ 1 2 3 4 5 1];
B = [ 1 0 2 0 2 3 4 0 5 1];
Is there a simple way to find array A within array B?
The use case for this simple example is I'm trying to detect changes to an array that are a result of inserting values into the original array.
In the example arrays provided, B is simply A with the array [0 2 0] inserted at index 2 and the array [0] inserted at the second to last index. Is there a robust way to know that array A is "dispersed" in array B at indices 1,5,6,7,9,10?
Note that I can't use ismember() because of the possible repetition of values in the "original" array as well as the "updated" array

回答 (1 件)

Thiago Henrique Gomes Lobato
Thiago Henrique Gomes Lobato 2021 年 4 月 25 日
編集済み: Thiago Henrique Gomes Lobato 2021 年 4 月 25 日
You could trace the first array on the second backwards:
A = [ 1 2 3 4 5 1];
B = [ 1 0 2 0 2 3 4 0 5 1];
positions = zeros(1,length(A));
idxInA = length(A);
for idx =length(B):-1:1
if A(idxInA) == B(idx)
positions(idxInA) = idx;
idxInA = idxInA-1;
if idxInA<1
break
end
end
end
positions
positions = 1×6
1 5 6 7 9 10
B(positions)
ans = 1×6
1 2 3 4 5 1
The only issue, which also happens in your example, is the ambiguity. For example, B can have an extra [0,2,0] after 1 or an extra [0] after 1 and an extra [0,2] after 2. Doing backwards as I did gives the answer you want, but you could as well have calculate it forward, so make sure you know what exactly you want to achieve. If the only goal is to see if A is in B in the right order, than it shouldn't matter

カテゴリ

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