Summing all elements in matlab without using a colon operator

I want to summarize all matrix elements in Matlab. If I had a matrix A, then I can sum all the elements by calling

sum(A(:));

But I would like to summarize the elements returned from such a function:

sum(gammaln(A))  % where gammaln is the logarithm of gamma function

Of course, I can do this in two steps:

B = gammaln(A);
sum(B(:));

But here I create a matrix B, which I do not need at all. And also I can do it as follows:

sum(sum(gammaln(A)))

But the number of sums will be equal to the dimension of my matrix. It looks ugly, and the size of the matrix can change.

I am curious if there is a way to do this.

+5
source share
1 answer

use reshapeinstead of operator (:):

sum(reshape(gammaln(A),[],1))
+14
source

All Articles