如何在MATLAB中分离if和else [英] how to separate if and else in 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 and else,我将得到答案相同,那是什么问题呢?我正在使用if和else来避免log(0),但是有一些问题.
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.
推荐答案
如果f,y是实值而不是整数,我建议使用
If f,y are real valued and not integers I would recommend using for example
abs(f(i)-1)< = eps
abs(f(i)-1) <= eps
其中eps是一个小数字"(例如eps = 1e-5
)
代替
where eps is a 'small number' (e.g eps = 1e-5
)
instead of
f(i)== 1
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
通过利用Matlab的矢量化表达功能,更紧凑,更高效(我宁愿为了可读性而牺牲一些额外的行):
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);
这篇关于如何在MATLAB中分离if和else的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!