Comparing columns of two sparse matrices
Show older comments
Hello. I want to do the following... Input: two sparse matrices A,B. Output: sparse matrix C, with C(i,j)=1 exactly when the ith column of A is equal to the jth column of B. The quickest code I have so far is this one:
r=[];
c=[];
for i=1:size(A,2)
for j=1:size(B,2)
if isequal(A(:,i),B(:,j))
r=[r,i];
c=[c,j];
end
end
end
C=sparse(r,c,ones(1,length(r)));
But for big matrices it gets very slow. Is there a way to make it run faster?
cheers
Accepted Answer
More Answers (1)
Walter Roberson
on 21 Jan 2016
[Arows, Acols] = find(A);
[Brows, Bcols] = find(B);
AUcols = unique(Acols);
BUcols = unique(Bcols);
matches = bsxfun(@(I,J) isequal(A(:,I), B(:,J)), AUcols(:), BUcols(:).');
[matches_rows, matches_cols] = find(matches);
C = sparse(AUcols(matches_rows), BUcols(matches_cols), 1);
3 Comments
Chris Jänkel
on 22 Jan 2016
Walter Roberson
on 22 Jan 2016
[Arows, Acols] = find(A);
[Brows, Bcols] = find(B);
AUcols = unique(Acols);
BUcols = unique(Bcols);
[GridA, GridB] = ndgrid(AUcols, BUcols);
matches = arrayfun(@(I,J) isequal(A(:,I), B(:,J)), GridA, GridB);
[matches_rows, matches_cols] = find(matches);
C = sparse(AUcols(matches_rows), BUcols(matches_cols), 1);
Chris Jänkel
on 22 Jan 2016
Categories
Find more on Creating and Concatenating Matrices 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!