Morten
Morten

Reputation: 23

Determining if any duplicate rows in two matrices in MatLab

Introduction to problem:

I'm modelling a system where i have a matrix X=([0,0,0];[0,1,0],...) where each row represent a point in 3D-space. I then choose a random row, r, and take all following rows and rotate around the point represented by r, and make a new matrix from these rows, X_rot. I now want to check whether any of the rows from X_rot is equal two any of the rows of X (i.e. two vertices on top of each other), and if that is the case refuse the rotation and try again.

Actual question:

Until now i have used the following code:

X_sim=[X;X_rot];
if numel(unique(X_sim,'rows'))==numel(X_sim);
    X(r+1:N+1,:,:)=X_rot;
end

Which works, but it takes up over 50% of my running time and i were considering if anybody in here knew a more efficient way to do it, since i don't need all the information that i get from unique.

P.S. if it matters then i typically have between 100 and 1000 rows in X.

Best regards, Morten

Additional: My x-matrix contains N+1 rows and i have 12 different rotational operations that i can apply to the sub-matrix x_rot:

step=ceil(rand()*N);
r=ceil(rand()*12);
x_rot=x(step+1:N+1,:);
x_rot=bsxfun(@minus,x_rot,x(step,:));
x_rot=x_rot*Rot(:,:,:,r);
x_rot=bsxfun(@plus,x_rot,x(step,:));

Upvotes: 2

Views: 123

Answers (2)

Andrew Janke
Andrew Janke

Reputation: 23858

How about ismember(X_rot, X, 'rows')?

Upvotes: 1

Luis Mendo
Luis Mendo

Reputation: 112659

Two possible approaches (I don't know if they are faster than using unique):

  1. Use pdist2:

    d = pdist2(X, X_rot, 'hamming'); %// 0 if rows are equal, 1 if different.
    %// Any distance function will do, so try those available and choose fastest
    result = any(d(:)==0);
    
  2. Use bsxfun:

    d = squeeze(any(bsxfun(@ne, X, permute(X_rot, [3 2 1])), 2));
    result = any(d(:)==0);
    

result is 1 if there is a row of X equal to some row of X_rot, and 0 otherwise.

Upvotes: 2

Related Questions