Zanam
Zanam

Reputation: 4807

Combine Matlab Arrays based on first column

I have 2 arrays:

array A (4x2):

1 2
4 13
5 14
6 13

array B (3x2):

2 11
4 34  
7 56

I want to get (6x3):

1  2
2      11
4  13  34
5  14
6  13
7      56

i.e. combine above 2 arrays of unequal size based on elements in first column and create a new array with columns of 2 arrays as distinct columns.

Thanks

Upvotes: 1

Views: 120

Answers (1)

Dan
Dan

Reputation: 45752

You can do it like this:

c = unique([a(:,1); b(:,1)]);
c(:,2:3) = NaN;
c(ismember(c(:,1), a(:,1)), 2) = a(:,2);
c(ismember(c(:,1), b(:,1)), 3) = b(:,2)

Upvotes: 1

Related Questions