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

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.
Thanks a lot in advance.
Benson

Answers (2)

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 Comments

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

Sign in to comment.

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 Comments

Hi, Matt,
Thanks a lot for your great help. I tested and compared the three sets of codes on my case. I found the original code is still little bit faster than your second code. Here is the comparison:
  1. Original code: 0.393 seconds
  2. Your first code: 0.521 seconds
  3. Your second code: 0.424 seconds
Thanks a lot any way.
Benson
But you must admit, my results show that it should be faster. Did you use the profiler to make sure that this operation was your bottleneck?
Yes, I am using profile to find the operations which takes longer time than I can stand. The above time I compared are from profile viewer.
Another bottkeneck is find. I used find several times, but it took much longre time than other operations. I do not know if you have a faster way to replace find.
Thanks.
Benson
I do not know if you have a faster way to replace find.
Yes, don't use it. Use logical indexing instead.
"I do not know if you have a faster way to replace find."
Answers and comments on your previous threads related to FIND:
Have you considered using logical indexing?

Sign in to comment.

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Asked:

on 7 Jul 2021

Commented:

on 9 Jul 2021

Community Treasure Hunt

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

Start Hunting!