I have two matrices `A` and `B` in Matlab. A has dimension `mx6`, e.g.

```
A=[  1     1     1     1   |  1     0;
     1     1     1     2   |  1     0;
     1     1     1     3   |  1     0;
     1     1     1     4   |  1     0;
     1     2     3     2   |  1     0;
     1     2     3     3   |  1     0;
     1     2     3     4   |  1     0]

```

`B` has dimension `nx6`, e.g.

```
B=[  1     1     1     1   |  1     1;
     1     2     3     1   |  1     1]

```

I want to merge `A` and `B` and create the matrix `C` following these steps without using loops: 

1) Consider `B(i,1:4)`; if there exists `j` such that `A(j,1:4)` is equal to `B(i,1:4)` [this can happen for at most one `j`] then `C(i,:)=[B(i,1:4) A(j,5)+B(i,5) A(j,6)+B(i,6)]`. Do this for all `i=1,...,n`. 

2) Fill the remaining rows of `C` with the rows of `A` and `B` that cannot be matched according to step 1). 

In the example

```
C=[  1     1     1     1   |  2     1;  %Step 1) above
   ------------------------------------
     1     1     1     2   |  1     0;  %Step 2) above
     1     1     1     3   |  1     0;  %firstly rows from A
     1     1     1     4   |  1     0;
     1     2     3     2   |  1     0;
     1     2     3     3   |  1     0;
     1     2     3     4   |  1     0; 
     1     2     3     1   |  1     1]  %lastly rows from B

```

My attempt using loops: 

```
%STEP 1
     for i=1:size(B,1)
            for j=1:size(A,1)
                if all(B(i,1:4)==A(j,1:4),2)
                   C(i,:)=[B(i,1:4) A(j,5)+B(i,5) A(j,6)+B(i,6)]
                end
            end
        end

 %STEP 2

  C=[ C; A(logical(1-ismember(A(:,1:4), B(:,1:4),'rows')),:)];
  C=[ C; B(logical(1-ismember(B(:,1:4), A(:,1:4),'rows')),:)]; 

```