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 CenterFile Exchange에서 Logical에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by