Flos
Flos

Reputation: 56

Selecting rows of matrix by value of first column

Let's say I have a matrix A, whose first column are IDs, and a vector B, containing certain IDs in a random order (and some of them might be missing etc). How do I select the rows of A with matching IDs in the order given by B?

Example:

Using the matrices

A = [2, 0.4, 0.3;
     9, 0.2, 0.8;
     3, 0.3, 0.4;
     5, 0.1, 0.5];
B = [9; 2; 5];

I would like to get the matrix

C = [9, 0.2, 0.8;
     2, 0.4, 0.3;
     5, 0.1, 0.5];

Upvotes: 1

Views: 242

Answers (2)

knedlsepp
knedlsepp

Reputation: 6084

If your IDs are unique, positive integers, you could do the following:

Approach #4 [ With sparse and indexing]

Construct a sparse vector that corresponds to the mapping: ID -> rowIndex and evaluate this vector:

indexOfID = sparse(A(:,1), 1, 1:size(A,1));
C = A(indexOfID(B),:);

This could be beneficial, when you want to query your IDs more than once, as you only have to build indexOfID once. (Also I do like the syntax of the "function evaluation" indexOfID(B))

Upvotes: 2

Divakar
Divakar

Reputation: 221754

As per the revised stated problem, the first column of A are the IDs and B also contains certain IDs and we need to match A's IDs with those of B's and select the matching rows from A. Based on such an assumption, you can few approaches here.

Approach #1 [ With ismember]

[~,idx] = ismember(B,A(:,1))
C = A(idx,:)

Approach #2 [ With bsxfun]

[idx,~] = find(bsxfun(@eq,A(:,1),B'))
C = A(idx,:)

Approach #3 [ With intersect]

[~,~,idx] = intersect(B,A(:,1),'stable')
C = A(idx,:)

Upvotes: 4

Related Questions