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

1 view (last 30 days)
Nadatimuj
Nadatimuj on 26 Jun 2022
Commented: Walter Roberson on 27 Jun 2022
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 Comments
Walter Roberson
Walter Roberson on 27 Jun 2022
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.

Sign in to comment.

Answers (2)

Walter Roberson
Walter Roberson on 26 Jun 2022
Switching to columns can improve performance as it allows better use of hardware cache.
  2 Comments
Walter Roberson
Walter Roberson on 27 Jun 2022
When I test on my system, the sum(a,1) version is 5 to 6 times faster than the sum(a,2) version

Sign in to comment.


MJFcoNaN
MJFcoNaN on 26 Jun 2022
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 Comment
Nadatimuj
Nadatimuj on 26 Jun 2022
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.

Sign in to comment.

Tags

Products


Release

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by