2014-10-31 247 views

回答

8

创建-3和2之间的随机整数,但随着3S更换零:

x = randi([-3,2],4);x(x==0)=3 
4

可以使用迭代的方法来检查零和与内同一个较小的组随机化的元素替换它们间隔[-3,3]。我们继续这样做,直到没有零。

的代码来实现这样一种做法是这样的 -

N = 4; %// datasize 
x1 = randi([-3,3],N); %// the first set/iteration of random numbers 

done = false; %// flag to detect if any zeros are left after iterative substitution 
while ~done %// keep the loop running until no zeros are found 
    x1((x1==0)) = randi([-3,3],numel(find(x1==0)),1); %// substitute zeros with 
               %// smaller set of random numbers 
    done = all(x1(:)~=0); 
end 
+1

这是正确的吗?我的意思是,概率图。 David所提出的解决方案以相同的概率对数字进行包装,然后改变“索引”或值之一。他不应该有更高的3的数量。对?或者我错过了什么? – 2014-10-31 10:47:33

+0

@AnderBiguri是的,第二个情节是大卫的方法。 – Divakar 2014-10-31 10:48:52

+1

我明白了,但我正在试着去理解(我真的在统计中)为什么他有更高的3。 – 2014-10-31 10:49:50

7

@大卫为您的具体问题很好地解决。但下面的解决方案适用于任何一组数字(注意,它们不需要是整数),尽管我已经为您的具体问题进行了设置。

OutputSize = [20, 1]; %Size of output matrix 
A = [-3; -2; -1; 1; 2; 3]; %Vector of numbers you want to sample from (can be whatever you want) 
x = A(randi(length(A), OutputSize)); %We randomly select the indices of A 

你可能希望把上述与输入AOutputDim功能。

,你可以使用此方法的单元阵列的甚至重新样品元件...

编辑:调整的代码,以允许任意尺寸的输出数组@Divakar的评价建议以下

+1

非常聪明的做法!而且似乎也是均匀分布的! +1为一个伟大的工作! – Divakar 2014-10-31 10:09:05

+1

另外,由于OP正在寻找'N×N'数组,为什么不使用'[N N]'来代替? – Divakar 2014-10-31 10:10:10

+0

@Divakar谢谢,并有很好的建议。我更进了一步,允许用户指定任何大小的输出数组。 – 2014-10-31 10:38:24

2

也许不是最快的解决方案,但有一个在统计工具箱randsample功能做到了这一点:

m = 4; %// number of rows 
n = 4; %// number of columns 
values = [-3:-1, 1:3]; %// values to sample from 
x = reshape(randsample(values, m*n, true), [m n]);