Zanam
Zanam

Reputation: 4807

Generating matlab array from two arrays

I have two large arrays which I will illustrate using the following examples.

The first array A is:

[ 1 21;
  3 4;
  4 12;
  5 65 ];

The second array B is:

[ 1 26;
  31 56;
  4 121;
  5 54 ];

I want to obtain the final array C as following:

[ 1 21 26;
  4 12 121;
  5 65 54];

i.e. use the common elements of first column from A and B to sieve out the rows I want to extract from arrays A and B and generate C.

Upvotes: 1

Views: 93

Answers (2)

Divakar
Divakar

Reputation: 221684

bsxfun approach -

%// Slightly bigger and not-so-straightforward example to avoid any confusion
    A =[ 1 21;
    3 4;
    4 12;
    8 10
    5 65]

B = [ 1 26;
    31 56;
    4 121;
    5 54
    9 99
    8 88]

binmat = bsxfun(@eq,A(:,1),B(:,1).');%//'
[v1,v2] = max(binmat,[],2);
C = [A(any(binmat,2),:) B(nonzeros(v1.*v2),2:end)]

Output -

A =
     1    21
     3     4
     4    12
     8    10
     5    65

B =
     1    26
    31    56
     4   121
     5    54
     9    99
     8    88


C =
     1    21    26
     4    12   121
     8    10    88
     5    65    54

Upvotes: 2

Luis Mendo
Luis Mendo

Reputation: 112759

Use the two-output vesion of ismember:

[ii jj] = ismember(A(:,1), B(:,1));
C = [ A(ii,:) B(jj(ii),2) ];

Note that in the second line ii is a logical index, whereas jj(ii) is a standard (integer) index.

Upvotes: 2

Related Questions