# How to quickly calculate the sum of the transpose of a sparse matrix?

8 visualizzazioni (ultimi 30 giorni)
Benson Gou il 7 Lug 2021
Commentato: James Tursa il 9 Lug 2021
Dear All,
I have a very big sparse matrix A. I want to obtain the sum of its transpose of the selected columns in A. Here is my code:
B = A(:,selectedCol)';
sumA = sum(B);
I am wondering if there is a faster way to do the above calculation.
Benson
##### 1 CommentoMostra -1 commenti meno recentiNascondi -1 commenti meno recenti
James Tursa il 9 Lug 2021
What are the actual dimensions of A and selectedCol?

Accedi per commentare.

### Risposte (2)

Matt J il 7 Lug 2021
Modificato: Matt J il 7 Lug 2021
A=sprand(1e6,1e3,100/1e6); %Example
selectedCol=1:2:100;
tic;
B=sum( A(:,selectedCol)');
toc
Elapsed time is 0.010279 seconds.
tic
B=sum( A(:,selectedCol) ,2)';
toc
Elapsed time is 0.005409 seconds.
##### 2 CommentiMostra NessunoNascondi Nessuno
Benson Gou il 7 Lug 2021
Hi, Matt,
Thanks a lot for your great help. I tested your code, but I found it took longer time than the original code.
Thanks a lot again.
Benson
Matt J il 7 Lug 2021
Longer on my example?

Accedi per commentare.

Matt J il 7 Lug 2021
Depening on the size of selectedCols, it may also help to cast the operation as a matrix/vector multiplication
A=sprand(1e6,1e5,100/1e6);
selectedCol=1:10:size(A,2);
tic;
B=sum( A(:,selectedCol)');
toc
Elapsed time is 0.140409 seconds.
tic
B=sum( A(:,selectedCol) ,2)';
toc
Elapsed time is 0.182437 seconds.
z=false(size(A,2),1);
tic
x=z;
x(selectedCol)=1;
B=(A*x)';
toc
Elapsed time is 0.086501 seconds.
##### 5 CommentiMostra 3 commenti meno recentiNascondi 3 commenti meno recenti
Matt J il 9 Lug 2021
I do not know if you have a faster way to replace find.
Yes, don't use it. Use logical indexing instead.
Stephen23 il 9 Lug 2021
Modificato: Stephen23 il 9 Lug 2021
"I do not know if you have a faster way to replace find."
Have you considered using logical indexing?

Accedi per commentare.

### Categorie

Scopri di più su Resizing and Reshaping Matrices in Help Center e File Exchange

### Community Treasure Hunt

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

Start Hunting!

Translated by