union 的组合可以获取唯一元素,然后ismember 可以找到相应的位置。
请注意,这将允许 A 和 B 具有任意数量的 2 或更多列。
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