讓我們考慮下面的代碼如何分離,如果和其他人在MATLAB
function averageentropy=calculate(f,y)
count1=0;
count0=0;
n=length(f);
n1=0;
n0=0;
entrop1=0;
entrop2=0;
bigp=sum(f)/n;
for i=1:n
if f(i)==1 && y(i)==1
count1=count1+1;
end
end
for i=1:n
if f(i)==0 && y(i)==1
count0=count0+1;
end
end
for i=1:n
if f(i)==1
n1=n1+1;
end
end
for i=1:n
if f(i)==0
n0=n0+1;
end
end
smallpplus=count1/n1;
smallpminus=count0/n0;
if smallpplus==0
entrop1=0;
else
entrop1=-smallpplus*log2(smallpplus)-(1- smallpplus)*log2(1- smallpplus);
end
if smallpminus==0
entrop2=0;
else
entrop2=-smallpminus*log2(smallpminus)-(1- smallpminus)*log2(1- smallpminus);
end
averageentropy=bigp*entrop1+(1-bigp)*entrop2
end
當我運行這段代碼,我得到0.4056,而在Excel中相同的程序返回我約0.91,這意味着有在if和else情況下是一些錯誤,因爲如果我刪除if和else,我得到的答案是相同的,那麼問題是什麼?我使用if和else來避免log(0),但是有一些問題。
您是否在代碼中設置了斷點以查看您是否始終在if或else中? – Vuwox
在MATLAB編輯器中選擇_all_代碼,然後按CTRL + I。 – chappjc
輸入是什麼?你如何知道Wxcel正在給出正確答案?如果你可以展示你的excel實現,也許我們可以幫助你找出差異 - 你想要做什麼的描述不是很清楚... – Floris