MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn moreOpportunities for recent engineering grads.

Apply Today
Asked by Daniel on 20 Dec 2011

Hello I am looking for a (simple) way to get the index of a row in which two (or n) values exist

example: looking for 4 and 5 in

[1 5 6; 5 4 3; 9 4 2]

will give me 2, because only row 2 has both 4 and 5 in it

Thanks

Daniel

*No products are associated with this question.*

Answer by Robert Cumming on 21 Dec 2011

Accepted answer

similar to the intersect answer - but I recoded intersect as its quite slow:

x=[1 2 3;4 5 6;3 2 1]; [a b]=find(x==4); [c d]=find(x==5); index = c.*NaN; for kk=1:length(c) check = a(a==c(kk))'; if ~isempty ( check ) index(kk) = check; end end output = index(~isnan(index));

Answer by Malcolm Lidierth on 20 Dec 2011

>> x=[1 5 6; 5 4 3; 9 4 2]; >> [a b]=find(x==4); >> [c d]=find(x==5); >> intersect(a,c)

ans =

2

Answer by Jan Simon on 20 Dec 2011

X = [1 5 6; 5 4 3; 9 4 2] index = and(any(X == 4, 2), any(X == 5, 2));

[EDITED: Apply ANY along 2nd dim, thanks Cyclist!]

Answer by the cyclist on 20 Dec 2011

Trust but verify this code:

x = [1 5 6; 5 4 3; 9 4 2] want(1,1,:) = [4 5];

indexToDesiredRows = all(any(bsxfun(@eq,x,want),2),3) rowNumbers = find(indexToDesiredRows)

Answer by Sean de Wolski on 20 Dec 2011

How about `ismember` with a `for`-loop?

doc ismember

Example

A = [1 5 6; 5 4 3; 9 4 2]; want = [4 5];

szA = size(A,1); idx = false(szA,1);

for ii = 1:szA idx(ii) = all(ismember(want,A(ii,:))); end

*idx* will be a logical vector of rows with 4 and 5. If you want the numeric values:

find(idx)

This will be the most scalable method if say you want 10 different numbers to be present in each row. Calling `any`/ `intersect` / `all` that many times and/or using that many dimensions is not really feasible.

## 2 Comments

Direct link to this comment:http://www.mathworks.com/matlabcentral/answers/24414#comment_54102

thank you all for the answers

since all of your answers do what I wanted I'll choose the "winner" by:

1. short code

2. running time

3. running time on large matrices and/or many numbers to find

Direct link to this comment:http://www.mathworks.com/matlabcentral/answers/24414#comment_54112

I deleted my answer so it will be easier for you to make a decision.