1
votes

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];
2
@knedlsepp I think the linked question's answer(s) might solve it with sorting needed thereafter. Of course, this is assuming OP here wants to use the vector as an indexing array. - Divakar
Ok maybe it wasn't so clear. A contains two columns, one is an ID, the other one is a value. B just contains ID in a certain order. B doesn't contain the index I want, but the Ids I want - Flos
@Flos Check out the posted solution then? Think you want something like that? - Divakar
if you don't care about the order: A(ismember(A(:,1),B),:) ---- if you do care about the order and the size of B is fixed to 3 ---- A([find(A(:,1)==B(1)), find(A(:,1)==B(2)), find(A(:,1)==B(3))],:) - yakoudbz

2 Answers

4
votes

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,:)
2
votes

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))