Building a connectivity matrix from one-to-many columns
Show older comments
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 Comments
Sean de Wolski
on 1 Feb 2012
I don't understand why 1,3 = 1. Can you provide the _actual_ resulting matrix and use numbers instead of letters in B (or provide scalars for those letters).
Walter Roberson
on 2 Feb 2012
1,3 = 1 because 1 maps to b (position 2) and 3 maps to b (position 6)
Neil
on 6 Feb 2012
Answers (1)
Sean de Wolski
on 6 Feb 2012
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
?
Categories
Find more on Time Series Objects 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!