How to find the common values of ith row and the rest of the rows in a matrix?
Show older comments
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
More Answers (1)
Geoff Hayes
on 27 Jun 2014
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.
Categories
Find more on Mathematics in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!