Comparing columns of two sparse matrices
Afficher commentaires plus anciens
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
Réponse acceptée
Plus de réponses (1)
Walter Roberson
le 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 commentaires
Chris Jänkel
le 22 Jan 2016
Walter Roberson
le 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
le 22 Jan 2016
Catégories
En savoir plus sur Creating and Concatenating Matrices dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!