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.
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.
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 .
use reshape
instead of (:)
operator:
sum(reshape(gammaln(A),[],1))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With