C.Colden
C.Colden

Reputation: 627

Find unique pairs in a matrix

Let's assume I have the following matrix:

A = [1 1 2 1;1 2 2 1;2 1 3 0;2 2 2 0;3 1 2 1]

Where the first column is an index and the next two an interaction and the last one a logic saying yes or no. So know I would like to generate the following heat map based on the interactions. "X" axis represents interactions and "Y" axis represents index.

   1-2  1-3  2-2
1   1   NaN   1
2  NaN   0    0
3   1   NaN  NaN

My current approach:

B = sortrows(A,[2,3]);

Afterwards I apply find for each row and column individually.

Is there a function similar to unique which can check for two columns at the same time?

Upvotes: 3

Views: 329

Answers (3)

rahnema1
rahnema1

Reputation: 15837

this is a possible solution with the aid of @Jeon 's answer(Updated):

A = [1 1 2 1;1 2 2 1;2 1 3 0;2 2 2 0;3 1 2 1]
[~,IA,idx] = unique(A(:, [2, 3]), 'rows');
r = max(A(:,1));
c = numel(IA);
out= NaN(r,c );
out(sub2ind([r ,c], A(:,1),idx)) = A(:,4)

Upvotes: 1

Luis Mendo
Luis Mendo

Reputation: 112659

Here's a way, using unique(...,'rows'):

A = [1 1 2 1; 1 2 2 1; 2 1 3 0; 2 2 2 0; 3 1 2 1]; % data
[~, ~, jj] = unique(A(:,[2 3]),'rows'); % get interaction identifiers
B = accumarray([A(:,1) jj], A(:,4), [], @sum, NaN); % build result, with NaN as fill value

This gives

B =
     1   NaN     1
   NaN     0     0
     1   NaN   NaN

Upvotes: 7

Jeon
Jeon

Reputation: 4076

>> A

A =

     1     1     2     1
     1     2     2     1
     2     1     3     0
     2     2     2     0
     3     1     2     1

>> [C, IA, IC] = unique(A(:, [2, 3]), 'rows')

C =

     1     2
     1     3
     2     2

IA =

     1
     3
     2

IC =

     1
     3
     2
     3
     1

C is a set of unique pairs. IA is the corresponding index of C (i.e., C == A(IA, [2, 3])). IC is the corresponding index of each row (i.e., A(:, [2, 3]) == C(IC, :)).

Upvotes: 2

Related Questions