12

Given the matrix:

A = [1 2 3; 4 5 6; 7 8 9];
  1. How could you use a for loop to compute the sum of the elements in the matrix?
  2. Write a one line MATLAB command using the function sum to sum the matrix elements in A.

My answer:

1)

for j=1:3,
    for i=j:3,
        A(i,:) = A(i,:)+A(j+1,:)+A(j+2,:)
    end
end

2)

sum(A)

Are these the correct answers? I didn't know how to use if, while and for. Can anyone explain it to me?

2
  • 2
    These are really simple questions. A few minutes on Google with one of the innumerable tutorials would have saved the rest of us alot of time.
    – Marc
    Nov 13, 2009 at 19:46
  • 1
    Try to avoid using for-loops for calculating stuff in Matlab. Unless you really want to make things really slow or there is no other way. Jul 14, 2011 at 16:11

6 Answers 6

31

For very large matrices using sum(sum(A)) can be faster than sum(A(:)):

>> A = rand(20000);
>> tic; B=sum(A(:)); toc; tic; C=sum(sum(A)); toc
Elapsed time is 0.407980 seconds.
Elapsed time is 0.322624 seconds.
5
  • 1
    Nice find! Actually it even seems to be faster for nearly any size. Even for rand(100) the difference is significant on my system. (Though not for rand(10000,1)). However, as it is about a fraction of a second I would still recommend the more robust/general sum(A(:)) for most purposes. Oct 8, 2013 at 14:56
  • @Dennis Jaheruddin I prefer sum(sum(A)) since it is more computationally efficient. The only advantage of sum(A(:)) is that it is easier to read but it recodes the whole matrix A into a vector, thus the computational effort. May 11, 2015 at 13:59
  • 1
    @MarioReutter Of course it is less efficient (as shown in the answer), but actually the main reason why I use it is that it works for matrices of higher dimensionality as well. Suppose you have M=rand(3,3,3), now compare sum(sum(M))) with sum(M(:)). May 26, 2015 at 11:29
  • Update: using Matlab 2015b, the difference is roughly an order of magnitude smaller (0.193 sec. v. 0.185 sec.). Mar 16, 2016 at 19:38
  • timeit(@()sum(sum(A)))/timeit(@()sum(A(:))) is more accurate than tic and toc.
    – bers
    Mar 31, 2016 at 18:07
18

1)

total = 0;
for i=1:size(A,1)
  for j=1:size(A,2)
    total = total + A(i,j);
  end
end

2)

total = sum(A(:));
2
  • 10
    And if you use 1) instead of 2) when you are actually using MATLAB for something real, then you need to die a slow horrible death ;) Nov 13, 2009 at 18:44
  • 1
    While a correct answer, I would hope to see the most up-ed answer to discourage loops. They do indeed lead to slow horrible deaths... Maybe edit it?
    – Argyll
    Apr 8, 2014 at 6:25
11

Another answer for the first question is to use one for loop and perform linear indexing into the array using the function NUMEL to get the total number of elements:

total = 0;
for i = 1:numel(A)
  total = total+A(i);
end
3

Avoid for loops whenever possible.

sum(A(:))

is great however if you have some logical indexing going on you can't use the (:) but you can write

% Sum all elements under 45 in the matrix
sum ( sum ( A *. ( A < 45 ) )

Since sum sums the columns and sums the row vector that was created by the first sum. Note that this only works if the matrix is 2-dim.

2

The best practice is definitely to avoid loops or recursions in Matlab.

Between sum(A(:)) and sum(sum(A)). In my experience, arrays in Matlab seems to be stored in a continuous block in memory as stacked column vectors. So the shape of A does not quite matter in sum(). (One can test reshape() and check if reshaping is fast in Matlab. If it is, then we have a reason to believe that the shape of an array is not directly related to the way the data is stored and manipulated.)

As such, there is no reason sum(sum(A)) should be faster. It would be slower if Matlab actually creates a row vector recording the sum of each column of A first and then sum over the columns. But I think sum(sum(A)) is very wide-spread amongst users. It is likely that they hard-code sum(sum(A)) to be a single loop, the same to sum(A(:)).

Below I offer some testing results. In each test, A=rand(size) and size is specified in the displayed texts.

First is using tic toc.

Size 100x100
sum(A(:))
Elapsed time is 0.000025 seconds.
sum(sum(A))
Elapsed time is 0.000018 seconds.

Size 10000x1
sum(A(:))
Elapsed time is 0.000014 seconds.
sum(A)
Elapsed time is 0.000013 seconds.

Size 1000x1000
sum(A(:))
Elapsed time is 0.001641 seconds.
sum(A)
Elapsed time is 0.001561 seconds.

Size 1000000
sum(A(:))
Elapsed time is 0.002439 seconds.
sum(A)
Elapsed time is 0.001697 seconds.

Size 10000x10000
sum(A(:))
Elapsed time is 0.148504 seconds.
sum(A)
Elapsed time is 0.155160 seconds.

Size 100000000
Error using rand
Out of memory. Type HELP MEMORY for your options.

Error in test27 (line 70)
A=rand(100000000,1);

Below is using cputime

Size 100x100
The cputime for sum(A(:)) in seconds is 
0
The cputime for sum(sum(A)) in seconds is 
0

Size 10000x1
The cputime for sum(A(:)) in seconds is 
0
The cputime for sum(sum(A)) in seconds is 
0

Size 1000x1000
The cputime for sum(A(:)) in seconds is 
0
The cputime for sum(sum(A)) in seconds is 
0

Size 1000000
The cputime for sum(A(:)) in seconds is 
0
The cputime for sum(sum(A)) in seconds is 
0

Size 10000x10000
The cputime for sum(A(:)) in seconds is 
0.312
The cputime for sum(sum(A)) in seconds is 
0.312

Size 100000000
Error using rand
Out of memory. Type HELP MEMORY for your options.

Error in test27_2 (line 70)
A=rand(100000000,1);

In my experience, both timers are only meaningful up to .1s. So if you have similar experience with Matlab timers, none of the tests can discern sum(A(:)) and sum(sum(A)).

I tried the largest size allowed on my computer a few more times.

Size 10000x10000
sum(A(:))
Elapsed time is 0.151256 seconds.
sum(A)
Elapsed time is 0.143937 seconds.

Size 10000x10000
sum(A(:))
Elapsed time is 0.149802 seconds.
sum(A)
Elapsed time is 0.145227 seconds.

Size 10000x10000
The cputime for sum(A(:)) in seconds is 
0.2808
The cputime for sum(sum(A)) in seconds is 
0.312

Size 10000x10000
The cputime for sum(A(:)) in seconds is 
0.312
The cputime for sum(sum(A)) in seconds is 
0.312

Size 10000x10000
The cputime for sum(A(:)) in seconds is 
0.312
The cputime for sum(sum(A)) in seconds is 
0.312

They seem equivalent. Either one is good. But sum(sum(A)) requires that you know the dimension of your array is 2.

2
  • Can someone shrink the size of the code boxes for me please? (If it's doable.)
    – Argyll
    Apr 8, 2014 at 6:23
  • 1
    The first is a comparison against sum(sum(A)), but all the rest are against just sum(A)... Aug 10, 2014 at 2:24
0

You are trying to sum up all the elements of 2-D Array

In Matlab use

Array_Sum = sum(sum(Array_Name));

1
  • 4
    Although this is not incorrect, better answers with the same information were posted months ago (Mohsen's in particular).
    – nkjt
    Apr 2, 2014 at 11:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.