在下面的代码,我希望确保有偶数theImageRand等于theImage或theImage2的机会,但我意识到,在1和100之间有更多数字等于2模1比2模0,所以被选择theImage不成比例的时间.
这是我遇到的最简单的想法,但也许有一个功能可以做到这一点更容易?我也在想我能找到一个符合我要求的数字并把它放到randi(n)中.
xRand = randi(100);
if mod(xRand,2) == 1
theImageRand = theImage;
elseif mod(xRand,2) == 0
theImageRand = theImage2;
end
Run Code Online (Sandbox Code Playgroud)
如果我能更清楚地解释,请告诉我.提前致谢.
您的代码完全符合您的要求,但可以通过使用randi(2)和删除计算来简化它mod.但是,有必要解决更多问题......
mod(xRand,2) 减少1-100到0/1对于xRand介于1和100之间,结果mod(xRand,2)将在0和1上均匀分布,如您通过执行以下代码所示:
xRand = 1:100;
xMod = mod(xRand,2);
cnt1 = sum(xMod == 1) % results in 50
cnt0 = sum(xMod == 0) % results in 50 as well
Run Code Online (Sandbox Code Playgroud)
基本上,您的代码按预期工作,因为randi选择从1到100的均匀分布的数字.随后,mod将它们简化为二进制表示,由于映射是针对相等的bin进行的,因此仍然是均匀分布的.
randi(2)通过从头开始生成二进制集,可以简化生成这些均匀分布的二进制数的整个过程.为了达到这个目的,你可以使用randi(2)哪个直接给你1或者2作为rayryeng在他对这个问题的评论中指出的.
这会给你以下代码:
xRand = randi(2);
if xRand == 1
theImageRand = theImage;
elseif xRand == 2
theImageRand = theImage2;
end
Run Code Online (Sandbox Code Playgroud)
现在我们来看看这个问题的有趣部分:结果是否真的均匀分布?为了检查这一点,我们可以运行代码N时间,然后分析每个图像被选择的次数.因此,我们将1分配给第一个图像,将2分配给第二个图像并将结果存储在其中res.在for循环之后,我们取它们为1或2的元素之和.
N = 1000000;
theImage = 1;
theImage2 = 2;
res = zeros(N,1);
for n = 1:N
xRand = randi(2);
if xRand == 1
theImageRand = theImage;
elseif xRand == 2
theImageRand = theImage2;
end
% xRand = randi(100);
% if mod(xRand,2) == 1
% theImageRand = theImage;
% elseif mod(xRand,2) == 0
% theImageRand = theImage2;
% end
res(n) = theImageRand;
end
cnt1 = sum(res==1);
cnt2 = sum(res==2);
percentage1 = cnt1/N*100 % approximately 50
percentage2 = cnt2/N*100 % approximately 50 as well
Run Code Online (Sandbox Code Playgroud)
正如我们所看到的,percentage1以及percentage2大约50,这意味着两个图像同时获得周围的50%的时间选择.计算它们之间的差异可能会产生误导cnt1,cnt2因为如果N数量很大,这个数字可能很高.但是,如果我们在许多实现中观察到这种差异,则总体平均值将近似为零.此外,我们可以观察到您使用的代码也mod(randi(100),2)提供了50%的分布.它不像解决方案那样高效和直接randi(2),使用R2016a在我的机器上执行速度提高约15%.
底线:我建议使用randi(2)上面提出的,因为它更直观,更有效.观察到的差异归因于随机过程并使其自身与更多的实现相等.重要的是要考虑两个图像的百分比而不是绝对差异.