## Find a row in a matrix in faster way

on 29 Nov 2012

### Matt Fig (view profile)

Hi,

I have to compare two matrices: in detail, I have to find if each row of a matrix1 is contained in a matrix2. Then I have to store the corresponding positions in a vector.

The following is a trivial method and seems to be faster than ismember version.

```if true
t1=tic;
for m=1:size(matrix1,1)
for l=1:size(matrix2,1)
if(sum(xor(matrix1(m,:), matrix2(l,:)))==0)
vector(m)=l;
end
end
end
toc(t1)
end
```

ismember version.

```if true
t2=tic;
for m=1:size(matrix1,1)
index=ismember(matrix2,matrix1(m,:),'rows');
l=find(index);
vector(m)=l;
end
toc(t2)
end
```

Is there a way to speed up such computation? Thank

Image Analyst

on 29 Nov 2012
Matt Fig

### Matt Fig (view profile)

on 29 Nov 2012

IA, the methods do not return the same results unless both matrices are binary....

## Products

No products are associated with this question.

### Matt Fig (view profile)

on 29 Nov 2012
Edited by Matt Fig

### Matt Fig (view profile)

on 29 Nov 2012

Here is a faster method, in the script I use to compare:

```M1 = rand(1000,8)>.5;
M2 = rand(1000,8)>.5;
```
```tic  % Method 1, use XOR
V1 = zeros(1,size(M1,1));
for m=1:size(M1,1)
for n=1:size(M2,1)
if(sum(xor(M1(m,:), M2(n,:)))==0)
V1(m)=n;
end
end
end
toc
```
```tic  % Method 2, use ISMEMBER
V2 = zeros(1,size(M1,1));
for m=1:size(M1,1)
index=ismember(M2,M1(m,:),'rows');
n = find(index,1,'last');
if ~isempty(n)
V2(m)=n;
end
end
toc
```
```tic  % Method 3, use BSXFUN
V3 = zeros(1,size(M1,1));
for m=1:size(M1,1)
index=all(bsxfun(@eq,M1(m,:),M2),2);
n = find(index,1,'last');
if ~isempty(n)
V3(m)=n;
end
end
toc
```
```isequal(V1,V2,V3)
```

Matt Fig

### Matt Fig (view profile)

on 30 Nov 2012

Hi,

thank you for your answer. I forgot to say that the matrices are binary I don't know if it makes some difference.

Thank you

Matt Fig

### Matt Fig (view profile)

on 30 Nov 2012

Did you see that I used binary matrices??

nedo nodo

### nedo nodo (view profile)

on 30 Nov 2012

Yes, thank you

#### Join the 15-year community celebration.

Play games and win prizes!

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

### Discover what MATLAB® can do for your career.

Apply Today

New to MATLAB?

Learn MATLAB today!