How to find the common values of ith row and the rest of the rows in a matrix?

What I want to do is to find the common elements between ith row and the rest of the rows.
Assume that we have the following matrix; A = [1 5 6 7 8 9 ; 2 4 5 3 6 11; 3 4 1 12 11 6; 4 5 6 12 13 14];
The first values of the first column is the ID, and the rest of the line of the each column is the values of each ID.
For i = 1, for instance, I need to find the common values of (1,2), (1,3) and (1,4).
ComVal(1,2) = 5; ComVal(1,3) = 6 ComVal(1,4) = 5,6
By the same token, the common values of other IDs should be found, which are:
ComVal(2,1) = 5; ComVal(2,3) = 4,6; ComVal(2,4) = 5,6;
ComVal(3,1) = 6; ComVal(3,2) = 4,6 ComVal(3,4) = 6,12
ComVal(4,1) = 5,6 ComVal(4,2) = 5,6 ComVal(4,3) = 6,12
Is there any possibility that I can do it without using a for loop?
Thanks in advance for the answers. Samet

 Accepted Answer

A = [1 5 6 7 8 9 ; 2 4 5 3 6 11; 3 4 1 12 11 6; 4 5 6 12 13 14];
n=size(A,1);
m=1:n;
for k=1:n
p=setdiff(m,k);
M=A(p,:);
R=ismember(M,A(k,:));
out{k}=arrayfun(@(x) M(x,R(x,:)),(1:n-1)','un',0);
end
celldisp(out)

1 Comment

It looks really good,with one minor problem. it also finds the first row, the IDs, as common values. We need to find the common values by comparing 2:size(A,1).

Sign in to comment.

More Answers (1)

If the idea is to find elements that are common to each row then you could try the following
% get the number of rows of A
[m] = size(A,1);
% pre-allocate memory to the cell output matrix (which is symmetric)
cellMtx = cell(m,m);
for u=1:m
for v=u+1:m
% determine the intersection between the two rows
cellMtx{u,v} = intersect(A(u,2:end),A(v,2:end));
cellMtx{v,u} = cellMtx{u,v};
end
end
Note that elements along the diagonal of cellMtx are empty as the above code skips those comparisons.

1 Comment

My code is almost same as what you wrote here. The problem is the data I have is really big, and using two for loops makes it too heavy. Apart from that code works perfectly fine.

Sign in to comment.

Categories

Find more on Mathematics in Help Center and File Exchange

Asked:

Sam
on 27 Jun 2014

Commented:

Sam
on 27 Jun 2014

Community Treasure Hunt

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

Start Hunting!