Given the matrix:
A = [1 2 3; 4 5 6; 7 8 9];
- How could you use a for loop to compute the sum of the elements in the matrix?
- Write a one line MATLAB command using the function
sum
to sum the matrix elements inA
.
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?
You are trying to sum up all the elements of 2-D Array
In Matlab use
Array_Sum = sum(sum(Array_Name));
1)
2)
For very large matrices using
sum(sum(A))
can be faster thansum(A(:))
:The best practice is definitely to avoid loops or recursions in Matlab.
Between
sum(A(:))
andsum(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 insum()
. (One can testreshape()
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 thinksum(sum(A))
is very wide-spread amongst users. It is likely that they hard-codesum(sum(A))
to be a single loop, the same tosum(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.
Below is using cputime
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(:))
andsum(sum(A))
.I tried the largest size allowed on my computer a few more times.
They seem equivalent. Either one is good. But
sum(sum(A))
requires that you know the dimension of your array is 2.Avoid for loops whenever possible.
is great however if you have some logical indexing going on you can't use the (:) but you can write
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.
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: