how to separate if and else in matlab

心已入冬 提交于 2019-12-11 20:22:53

问题


let us consider following code

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

when I am running this code, I am getting 0.4056, while in Excel the same procedure returns me approximately 0.91, which means that there is some error in if and else case, because if I remove if and else, I am getting the same answer to, so what is problem? I am using if and else to avoid log(0), but there is some problem.


回答1:


If f,y are real valued and not integers I would recommend using for example

abs(f(i)-1) <= eps

where eps is a 'small number' (e.g eps = 1e-5) instead of

f(i)==1

On a side note, you could write this part of your code:

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

more compactly and efficiently by taking advantage of Matlab's vectorized expression capabilities (I preferred to sacrifice some extra lines for the sake of readability):

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


来源:https://stackoverflow.com/questions/20006964/how-to-separate-if-and-else-in-matlab

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!