Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

summing all elements in matlab without using colon operator

Tags:

matlab

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

sum(A(:));

But I would like to sum elements returning from a function like this:

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 B matrix, which I don't need at all. And also I can do it this way:

sum(sum(gammaln(A)))

But, the number of sum's will be equal to the dimension of my matrix. It looks ugly, and the matrix dimension may change.

I'm curious if there is any way of doing this.

like image 938
Caveman Avatar asked Mar 05 '12 09:03

Caveman


People also ask

How do you sum all elements in Matlab?

S = sum( A , 'all' ) computes the sum of all elements of A . This syntax is valid for MATLAB® versions R2018b and later. S = sum( A , dim ) returns the sum along dimension dim . For example, if A is a matrix, then sum(A,2) is a column vector containing the sum of each row.

Is there a summation function in Matlab?

F = symsum( f , k , a , b ) returns the sum of the series f with respect to the summation index k from the lower bound a to the upper bound b . If you do not specify k , symsum uses the variable determined by symvar as the summation index. If f is a constant, then the default variable is x .


1 Answers

use reshape instead of (:) operator:

sum(reshape(gammaln(A),[],1))
like image 55
zenpoy Avatar answered Nov 15 '22 06:11

zenpoy