MATLAB Answers

Rikke
0

How to make a new array based on two arrays?

Asked by Rikke
on 14 Apr 2019
Latest activity Commented on by Rikke
on 15 Apr 2019
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.

  0 Comments

Sign in to comment.

1 Answer

Answer by Walter Roberson
on 14 Apr 2019
 Accepted Answer

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

Thank you for your respons!
I want it to produce [nan 4 5 nan nan nan 6 7]. I forgot to say that actually every number in the array are different, so for example 4 and 5 will never show up twice (even though the example I wrote didn't show that). And also the nan can be a number as well, for example zero, it does't matter: [0 4 5 0 0 0 6 7]. As long as the array gets extended at the right place.
In the special case where the elements are unique, then
C = B .* ismember(B, A);
Thanks!

Sign in to comment.