Building a connectivity matrix from one-to-many columns

6 次查看(过去 30 天)
Hi All.
For a simpler example of what I am doing - I have two columns of data. They are both numbers, both 'n' in size. Say column A and column B.
Each element in column A, maps to the corresponding location in column B. The elements are not unique - one number will occur many times in column A, for instance, each time mapping to a unique value in column B (there are no repetitions).
For a given element in A, I want to find all of the corresponding mapping points in B.
I then want to build a matrix, where rows and columns correspond to IDs from A. The (i,j) position will then be equal to 1, if the i,j'th elements in A have a common mapping point in B.
For a small example,
A = [1 1 2 2 2 3 3] B = [a b a c d b d]
Then, '1' has a map in common (1 goes to a and b, and so on) with '2' - 'a' and '3' - 'b'. and '2' has a common point with '3' - 'd'. Then, the matrix would be:
(1,2) = 1, (2,3)=1, (1,3)=1. (it will be symmetric, so the order (1,2) or (2,1) doesn't matter).
I can do this with lots of loops, but if someone has a better way I would be thankful.
Neil.
  3 个评论
Walter Roberson
Walter Roberson 2012-2-2
1,3 = 1 because 1 maps to b (position 2) and 3 maps to b (position 6)
Neil
Neil 2012-2-6
As Walter says.
I thought I had an answer with a plethora of loops, but it seems I keep making mistakes. Hopefully I can still find an answer!
I think whether or not B contains letters or number isn't important - it is a one to many relationship from A to B that I want to express as a matrix. I could have numbers instead of letters in B, but all it all those values are simply labels for a set.
The numbers in A are the important ones - these are the values I will use as indices for my matrix. Therefore, the matrix is square with dimensions equal to the number of unique entries in A.

请先登录,再进行评论。

回答(1 个)

Sean de Wolski
Sean de Wolski 2012-2-6
So something like:
a = pi; %numbers;
b = 2.1;
c = 1.2;
d = 42;
A = [1 1 2 2 2 3 3]'; %column vectors
B = [a b a c d b d]';
Aacc = accumarray(A,B,[],@(x){x}); %build cell array of parts
[r c] = find(triu(true(numel(Aacc)),1)); %non diagonal coords
connmat = diag(cellfun('prodofsize',Aacc)); %make diagonal
for ii = 1:numel(r);
n = sum(ismember(Aacc{r(ii)},Aacc{c(ii)})); %number intersecting
connmat(r(ii),c(ii)) = n; %save
connmat(c(ii),r(ii)) = n;
end
?

类别

Help CenterFile Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by