Michael
Michael

Reputation: 290

Enter values to correct table cell (according to entry of first column) in MATLAB

I have a MATLAB array with R rows and C columns, where the first column contains numerical identifiers, which are not necessarily a set of ordered numbers.

Now, I load a second array with R' rows and 2 columns, where again the first column contains identifiers, while the second column contains numerical data. How can I efficiently write the data corresponding to identifier I into an additional column of the correspoding row (also identified by identifier I) of the original array?

Of course a trivial solution would be a construct of for loops and if-else or switch-case conditions, but I suppose there must be a more elegant, vectorized way to do it.

To further illustrate the problem:

A1 = [        %first array
      1, 0.3  
      2, 0.9
      3, 12];

A2 = [        %second array
      1, 0.5
      3, 9];

G = [         %goal
     1, 0.3, 0.5
     2, 0.9, NaN
     3, 12, 9];

Upvotes: 1

Views: 24

Answers (1)

Luis Mendo
Luis Mendo

Reputation: 112669

You can achieve that using ismember:

G = A1; % define G as A1
G(:,end+1) = NaN; % extend with a column of NaNs
[is, ind] = ismember(A2(:,1), A1(:,1)); % matchings of first column of A2 in A1,
                                        % and their indices
G(ind(is),end) = A2(is,2); % fill matched rows with values second column of A2

Note that:

  • This also works if some identifier in A2 is not present in A1.
  • If several rows of A2 have the same identifier, the value corresponding to the last one gets written into G.

Upvotes: 1

Related Questions