2013-11-15 72 views
0

讓我們考慮下面的代碼如何分離,如果和其他人在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),但是有一些問題。

+0

您是否在代碼中設置了斷點以查看您是否始終在if或else中? – Vuwox

+2

在MATLAB編輯器中選擇_all_代碼,然後按CTRL + I。 – chappjc

+0

輸入是什麼?你如何知道Wxcel正在給出正確答案?如果你可以展示你的excel實現,也許我們可以幫助你找出差異 - 你想要做什麼的描述不是很清楚... – Floris

回答

0

如果F,Y是實值和不是整數我建議使用例如

ABS(F(I)-1)< = EPS

其中的EPS「小數」(例如eps = 1e-5) 代替

F(1)== 1

在一個側面說明,你可以寫你的這部分代碼:通過利用Matlab的量化表達能力的優勢更加緊湊和有效

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 

(我寧願犧牲一些額外的線路爲可讀性的原因) :

indf1 = f == 1; 
indf0 = ~indf1 ; 
indy1 = y == 1; 
indy0 = ~indy1 ; 
count1 = sum(indf1 & indy1) ; 
count0 = sum(indf0 & indy1) ; 
n1 = sum(indf1); 
n0 = sum(indf0); 
+0

是它的原因嗎? –

+0

f或y是否包含真實值或僅包含整數? – Chris

+0

只是整數,0和1 –