For the following equation:
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.
For the following equation:
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.
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(:)) )
Here's how I would write that:
In Matlab we tend to avoid loops.
Considering the form of your equation, the two sums can be collapsed into one. In Matlab we can do that by using linear indexing.
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:
You have some parentheses wrong. The computed value is not that given by the equation.
You should avoid using i
and j
as variable names, as they override the imaginary unit (see here).
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;