0

For the following equation:

enter image description here

Do we write it in MATLAB as follows:

sum=0;
    for j=1:k
        for i=1:n
          sum = sum + (u(i,j)*log2(u(i,j)+(1-u(i,j)*log2(1-u(i,j)))))/n;  
        end
    end
    result = -1 * sum;

Thanks.

Simplicity
  • 47,404
  • 98
  • 256
  • 385

3 Answers3

2

to quote Jongware: no, that's not how we do it!

you rather write:

fun = @(x) x*log2(x)+(1-x)*log2(1-x);
result = -1/n*sum( arrayfun(fun,u(:)) )
Robert Seifert
  • 25,078
  • 11
  • 68
  • 113
1

Here's how I would write that:

  1. In Matlab we tend to avoid loops.

  2. Considering the form of your equation, the two sums can be collapsed into one. In Matlab we can do that by using linear indexing.

  3. Move the n out of the sum to reduce the number of operations.

So:

H = -sum(u(:).*log2(u(:))+(1-u(:)).*log2(1-u(:)))/n;

On the other hand, in your code:

  1. You have some parentheses wrong. The computed value is not that given by the equation.

  2. You should avoid using i and j as variable names, as they override the imaginary unit (see here).

  3. You should avoid using sum as a variable name, as it overrides Matlab's bulit.in function sum.

Community
  • 1
  • 1
Luis Mendo
  • 110,752
  • 13
  • 76
  • 147
0
sum=0;
for i=1:k
    for j=1:n
      sum = sum + (u(i,j)*log2(u(i,j)+(1-u(i,j)*log2(1-u(i,j)))))/n;  
    end
end
result = -1 * sum;
user3054997
  • 125
  • 3
  • 10