Comparing columns of two sparse matrices
Ältere Kommentare anzeigen
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
Akzeptierte Antwort
Weitere Antworten (1)
Walter Roberson
am 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 Kommentare
Chris Jänkel
am 22 Jan. 2016
Walter Roberson
am 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
am 22 Jan. 2016
Kategorien
Mehr zu Sparse Matrices finden Sie in Hilfe-Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!