matlabcrossover

Single point crossover


I have two array(matrix with one row) temp1 and temp2 as follow:

temp1=[1 2 3 4 5 6 7 8 9]
temp2=[10 11 12 13 14 15 16 17 18]

and I have an index pn=3. I need output as follows:

tempNew=[1 2 3 13 14 15 16 17 18]

i.e. how do I create tempNew such that all values on indices up to pn come from temp1 and all values beyond index pn come from temp2?


Solution

  • temp1=[1 2 3 4 5 6 7 8 9]
    temp2=[10 11 12 13 14 15 16 17 18]
    pn=3;
    tempNew = [temp1(1:pn),temp2(pn+1:end)]
    tempNew =
         1     2     3    13    14    15    16    17    18
    

    You use pn to create two temporary arrays to index both of your tempX arrays. Then simply concatenate them using square brackets.

    Indexing always starts at 1 in MATLAB, so 1:pn will give you the first pn values of an array. end signifies the end of an array, so pn+1:end will give you all values from index pn+1 up to the last one of an array.