Reputation: 960
Given a matrix A with dimension m x n and the entries in the matrix lies [0,1]
For example
A = [0.5 0 0 0.5 0
0 0.5 0 0 0.5
1 0 0 0 0]
I would like to calculate sum(sum(a_ij log(a_ij))), where a_ij is the i th row and j th col entry in the matrix A. Since there exist an 0 entry in the matrix, i always get NAN as a result.
How do i consider only non-zero entries to calculate sum(sum(a_ij log(a_ij))) [entropy of the matrix].
Upvotes: 2
Views: 7567
Reputation: 2342
If it is a very large array:
sum(A.*log(A+eps))
which should be faster than indexing.
Upvotes: 2
Reputation: 3116
To consider only specific elements of a matrix you can use logical indexing. For example if you only want to select non-zero entries of A you can use A(A~=0)
. So for your problem the solution can be written:
sum(A(A~=0).*log(A(A~=0)));
EDIT: wow that is some kind of coincidence, I've just seen your comment after posting this. Well, glad you've worked it out yourself.
Upvotes: 5