How to make a new array based on two arrays?

3 views (last 30 days)
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.

Accepted Answer

Walter Roberson
Walter Roberson on 14 Apr 2019
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 Comments
Walter Roberson
Walter Roberson on 15 Apr 2019
In the special case where the elements are unique, then
C = B .* ismember(B, A);

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!