MATLAB: Please help me implement the equations: Pij = (f(i,j))/(​∑_(i=1)^M∑​_(j=1)^N〖f​(i,j)〗) and H = ─∑_(i=1)^M​∑_(j=1)^NP​ijlog2Pij

Image Processing Toolboximage segmentation

Can someone please explain how to implement these equations in MATLAB?
Pij = (f(i,j))/(∑_(i=1)^M∑_(j=1)^Nf(i,j))
H = ─∑_(i=1)^M∑_(j=1)^NPijlog2Pij

Best Answer

It would be something like (provide your own functions for f, and set up the values of M and N),
clc;clear;close; % set up, clean up..
% start of Pij part: Pij = (f(i,j))/(∑_(i=1)^M∑_(j=1)^N〖f(i,j)〗)
M=...; N=...; % give values
function f=functionF(x,y)
% ... how to find f for x (x is imported i) and y (it is j )
end % function
Pij_single=zeros(M,N); P_of_J=zeros(1,M); % initialize P's
for i=1:M
for j=1:N
Pij_single(i,j)=functionF(i,j);
end
P_of_J(i)=sum(Pij_single(i,:));
end
Pij_sumOnly=sum(P_of_J); % it must be a single value
for i=1:M
for j=1:M
P(i,j)=functionF(i,j)./Pij_sumOnly;
end
end
% End of Pij part
% Start of H part: H = ─∑_(i=1)^M∑_(j=1)^NPijlog2Pij
clear P_single, P_of_J; % in case you need to save memory
H_of_J=zeros(1,M);Hij=zeros(N,M);
% Mark 1
% Note: if you need H = ─∑_(i=1)^M∑_(j=1)^NPijlog2Pij use the code in mark2.
% If you mean H = ─∑_(i=1)^(M-1)∑_(j=1)^(N-1)Pij*log2(Pij) use below:
H=entropy(Pij);
disp('H is: '); H
% Mark 2. Delete the lines below if not needed
for i=1:M;
for j=1:N
Hij(i,j)=P(i,j).*log2(P(i,j));
end
H_of_J(i)=sum(Hij(:,1));
end
H=-sum(H_of_J);
disp('H is: '); H
% End of the code. Double check initial indices of M, N please.
Related Question