How to make a new array based on two arrays?

조회 수: 3 (최근 30일)
Rikke
Rikke 2019년 4월 14일
댓글: Rikke 2019년 4월 15일
A=[1 4 3 1 5 9 1 11 14 15 16];
B=[1 4 3 1 5 6 7 8 9 1 11 12 13 14 15 16];
How to make a new array like this:
C=[1 4 3 1 5 nan nan nan 9 1 11 nan nan 14 15 16];
The new array are to be like A but in addition has nan where the numbers are missing so it will end up with the same length as B.

채택된 답변

Walter Roberson
Walter Roberson 2019년 4월 14일
You need a matching algorithm to find the best match. You can use dynamic programming, or you can use Boyer-Moore or one of the improvements of it.
You cannot just take the first available match. Your text clearly permits repetition, and therefore has to permit repetition (and partial repetition) of patterns. If you are positioned at [4 5 6 7] now and the target has [15 4 5 18 4 5 6 7] then if you match the first available 4 5 after the 15, then you only get to match 2 positions there, whereas if you held off judgement to beyond the 18 then you get to match 4 positions there. Is the "right" output [nan 4 5 nan nan nan 6 7] or is the "right" output [nan nan nan nan 4 5 6 7] ?
If you have the Bioinformatics Toolbox, you might be able to use https://www.mathworks.com/help/bioinfo/sequence-alignment.html Sequence Alignment -- but if you do, be sure to examine the assumptions it has about what the "best" sequence is. Would it produce the [nan 4 5 nan nan nan 6 7] or would it produce the [nan nan nan nan 4 5 6 7], and which is better for your purpose ?
  댓글 수: 3
Walter Roberson
Walter Roberson 2019년 4월 15일
In the special case where the elements are unique, then
C = B .* ismember(B, A);
Rikke
Rikke 2019년 4월 15일
Thanks!

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

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