Is there any other function faster than sum(A,2) to get the sum of all rows?

a=zeros(6750);
h=zeros(6750,1);
tic;k=h-sum(a,2); toc
Elapsed time is 0.041132 seconds.
Is there any faster way than to use sum(A,2) to get the sums of the rows of a matrix? sum(A,2) seems to be slow for large matrices.

4 Kommentare

  1. What's your definition of large? How many rows and columns?
  2. How long is it taking for those large matrices? How many seconds or minutes?
  3. How much speed do you require? What is the max allowable time?
  4. Do you have the Parallel Processing Toolbox?
Thanks for the queries.
  1. In my case, at max it can be 10000x10000 matrix. I used zeros just as an example, however, my matrix will usually have non-zero values but typically it is very sparse. I did not use sparse notation though.
  2. As you can see in the original post, for 6750x6750 matrix it takes 0.04 seconds here, on my computer it took 0.017 sec.
  3. miliseconds can be acceptable, 0.001 sec or so..
  4. Is it just an add-on? Then I can install it, but currently I don't.
The Parallel Processing Toolbox is an add-on toolbox. You can ask for a free trial of it and see if the Parallel Processing Toolbox helps. I know some functions recognize if you have that toolbox and start parallel processes going on multiple CPU cores on your computer automatically.
For sufficiently large matrices, addition is automatically handled by high performance parallel libraries. Using parfor or parfeval() will not improve performance compared to the automatic multi-core work that is done.

Melden Sie sich an, um zu kommentieren.

Antworten (2)

Walter Roberson
Walter Roberson am 26 Jun. 2022
Switching to columns can improve performance as it allows better use of hardware cache.

2 Kommentare

Thanks for the suggestion. Did you mean this? Doesn't look like to save too much time...
a=zeros(6750);
h=zeros(1,6750);
tic;k=h-sum(a,1); toc
Elapsed time is 0.033019 seconds.
When I test on my system, the sum(a,1) version is 5 to 6 times faster than the sum(a,2) version

Melden Sie sich an, um zu kommentieren.

In general, the native functions are optimized sufficiently.
In certain cases, there may be some better way but in other parts of code. For example,
a=sparse(zeros(6750));
h=sparse(zeros(6750,1));
tic;k=h-sum(a,2); toc
Elapsed time is 0.003234 seconds.

1 Kommentar

Thanks, yes that's a good idea. However, originally I didn't use the sparse notation, I will check if using sparse will impact other parts of the code. Otherwise sparse conversion just here can take some time.

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Hilfe-Center und File Exchange

Produkte

Version

R2022a

Tags

Gefragt:

am 26 Jun. 2022

Kommentiert:

am 27 Jun. 2022

Community Treasure Hunt

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

Start Hunting!

Translated by