0
votes

Say I have 2 arrays of double precision in matlab, how can I merge them with unknown offsets?

For example:

A = 
1 1
2 2
3 3
4 4
5 5

B = 
2 6
3 5
4 4
5 3
6 2

Is there a way to create from these two arrays a single array with 3 columns like below when I don't know the offset/overlap between A and B in terms of values in the first column?

C =
1 1 NaN
2 2 6
3 3 5
4 4 4
5 5 3
6 NaN 2

Is there an efficient way to do this?

The solution I've come up with right now is to piece together the first columns of A and B, and then proceed to use a for loop to iterate through.

2

2 Answers

2
votes

This seems to work. I'm a bit concerned about edge cases, not a lot of testing.

A = [...
     1     1; ...
     2     2; ...
     3     3; ...
     4     4; ...
     5     5];
B = [...
     2     6; ...
     3     5; ...
     4     4; ...
     5     3; ...
     6     2];

C1 = union(A(:,1), B(:,1));

C2 = nan(size(C1));
[~, ixsA] = ismember(A(:,1), C1);
C2(ixsA) = A(:,2);

C3 = nan(size(C1));
[~, ixsB] = ismember(B(:,1), C1);
C3(ixsB) = B(:,2);

C = [C1 C2 C3];
1
votes

A combination of union to get the unique elements then ismember to find the corresponding locations does the trick.

As a note, this will allow for A and B to have any number of columns 2 or greater.

A = [1 1;2 2;3 3;4 4;5 5];
B = [2 6;3 5;4 4;5 3;6 2];

%Get the elements from the first columns of A and B
C = union(A(:,1), B(:, 1));
%Prepopulate C to the correct size with NaN's
C = [C, nan(size(C,1), size(A,2) + size(B,2) - 2)];

%Find the rows of C where column 1 of A ended up
[~, i] = ismember(A(:,1), C(:,1));
%Stick the rest of A in those rows in the first set of free columns
C(i, 2:size(A,2)) = A(:,2:end);

%Now do the same with B in the second set of free columns
[~, i] = ismember(B(:,1), C(:,1));
C(i, size(A,2) + 1:end) = B(:,2:end);

C

C =

     1     1   NaN
     2     2     6
     3     3     5
     4     4     4
     5     5     3
     6   NaN     2