MATLAB: Why am i getting NaN from the function

entropyMATLABnan

i was asked to write a function that gets b&w image and returns its entropy. im not allowed to use im_hist or entrtopy (obviously).
this is the function i wrote:
function [Entropy] = EntropyCalc(image)
image_hist = histogram(image);
values = image_hist.Values;
[size_x, size_y] = size(image);
total = size_x * size_y;
p = values./total;
Entropy = – sum(p.*log2(p));
end
but i keep getting NaN.
any ideas??
thanks!

Best Answer

As David said your log2(p) is not safe, you can solve this problem by using this line of code:
Entropy = - sum(p.*log2(p+eps));