1

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.

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Congratz Luis! Your 1000th answer!
2

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

6 Comments

Our approaches give different results if for example the last two rows of B are interchanged. The OP should have clarified. But from the wording, it would appear order doesn't matter?
... Or perhaps you are missing a .' within bsxfun?
yeah that might be it! Thanks! My system running slow, I have like 30 something tabs open! And now I need to do some more processing.
I think you then need an any (because ind is now a column): C = [A(any(ind),:) B(...,2:end)]. And to index into B you may also need some changes; any(ind) may not work
The party wouldn't be he same without bsxfun:-)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.