Zanam
Zanam

Reputation: 4807

Generating matlab array from union and replacement of 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:

[ 3 56;
  5 121];

I want to obtain the final array C as following:

[ 1 21;
  3 56;
  4 12;
  5 121 ];

i.e. replace second column of A with elements of B when available.

I am using Matlab 2007.

Upvotes: 1

Views: 42

Answers (1)

Divakar
Divakar

Reputation: 221574

MATLAB Solution

With ismember -

C = A;
[is_present,pos] = ismember(A(:,1),B(:,1))
C(is_present,2) = B(pos(is_present),2)

Or use bsxfun to replace ismember -

[is_present,pos] = max(bsxfun(@eq,A(:,1),B(:,1).'),[],2);

Sample run -

>> A,B
A =
     1    21
     3     4
     4    12
     5    65
B =
     3    56
     5   121
     4    66
>> C = A;
[is_present,pos] = ismember(A(:,1),B(:,1));
C(is_present,2) = B(pos(is_present),2);
>> C
C =
     1    21
     3    56
     4    66
     5   121

Bonus: NUMPY/PYTHON Solution

You can use boolean indexing with np.in1d -

import numpy as np

mask = np.in1d(A[:,0],B[:,0])
C = A.copy()
C[mask] = B

Sample run -

In [34]: A
Out[34]: 
array([[ 1, 21],
       [ 3,  4],
       [ 4, 12],
       [ 5, 65]])

In [35]: B
Out[35]: 
array([[  3,  56],
       [  5, 121]])

In [36]: mask = np.in1d(A[:,0],B[:,0])
    ...: C = A.copy()
    ...: C[mask] = B
    ...: 

In [37]: C
Out[37]: 
array([[  1,  21],
       [  3,  56],
       [  4,  12],
       [  5, 121]])

Upvotes: 2

Related Questions