Intersection of matrix rows up to a given column

How can I find the number of intersecting elements of a matrix up to a user defined column? For example, intersection of first 3 elements. This is what I tried, but it is not working. Thx for the help.
r=[1 2 3 4 5 6; 2 3 4 5 6 1; 1 5 6 3 2 4];
d=3;
dist=pdist(r,@(a,b)length(intersect(a(:,1:d),b(:,1:d))))

 채택된 답변

Walter Roberson
Walter Roberson 2017년 7월 12일

1 개 추천

[A,B] = ndgrid(1:size(r,1),1:size(r,1));
dist = arrayfun(@(aidx,bidx)numel(intersect(r(aidx,1:d),r(bidx,1:d))), A, B);

댓글 수: 5

MB
MB 2017년 7월 13일
편집: MB 2017년 7월 13일
Thx for the answer but this is not what I am looking for and I don't think it is working properly. For example if d and row count are equal to 3 result must be 2 1 0.
  • There will be 3 comparisons. "2" (1-2-3 and 2-3-4 "2" elements match), "1" (1-2-3 and 1-5-6 "1" element match) and "0" (2-3-4 and 1-5-6 no elements match).
r=[1 2 3 4 5 6; 2 3 4 5 6 1; 1 5 6 3 2 4];
d=3;
[A,B] = ndgrid(1:size(r,1),1:size(r,1));
temp = arrayfun(@(aidx,bidx)numel(intersect(r(aidx,1:d),r(bidx,1:d))), A, B);
dist = squareform(temp - diag(diag(temp)));
MB
MB 2017년 7월 13일
편집: MB 2017년 7월 13일
Thx it is working perfectly fine much appreciated for your help but I wonder if it can be done by using "pdist" function because my code seems logical but it is not working.
dist=pdist(r,@(a,b) sum(ismember(b(:,1:d), a(:,1:d)),2))
"A distance function must be of form
d2 = distfun(XI,XJ)
taking as arguments a 1-by-n vector XI, corresponding to a single row of X, and an m2-by-n matrix XJ, corresponding to multiple rows of X. distfun must accept a matrix XJ with an arbitrary number of rows. distfun must return an m2-by-1 vector of distances d2, whose kth element is the distance between XI and XJ(k,:)."
MB
MB 2017년 7월 13일
Thank you this one is far too simple to interpret.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

질문:

MB
2017년 7월 12일

댓글:

MB
2017년 7월 13일

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by