Question: For the following equation:

![enter image description here](https://i.stack.imgur.com/BubSp.png)

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.

Answer: 
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](http://www.mathworks.es/company/newsletters/articles/matrix-indexing-in-matlab.html).
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](https://stackoverflow.com/questions/14790740/using-i-and-j-as-variables-in-matlab)).
3. You should avoid using `sum` as a variable name, as it overrides Matlab's bulit.in function `sum`.
```
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;

```