2015-10-26 44 views

回答

2

有几种方法可以做到这一点。

方法#1 - 从一个小阵列中选择

可以创建一个小的阵列,其包括[-1 1],然后创建包含1个或2个和索引插入此序列中的随机的整数:

N = 10; %// Number of values in the array 

%// Generate random indices 
ind = randi(2, N, 1); 

%// Create small array 
arr = [-1; 1]; 

%// Get final array 
out = arr(ind); 

方法#2 - 从统一的随机分布和阈值生成值

您也可以生成随机均匀分布的浮点值,并且大于0.5的任何值都可以设置为1,并且可以设置为1可以设置为-1。

N = 10; %// Number of values in the array 

%// Generate randomly distributed floating point values 
out = rand(N, 1); 

%// Find those locations that are >= 0.5 
ind = out >= 0.5; 

%// Set the right locations to +1/-1 
out(ind) = 1; 
out(~ind) = -1; 

方法#3 - 使用三角

您可以使用一个事实,即cos(n*pi)可以给予1或-1,这取决于什么价值n是只要n是一个整数。奇数值产生-1而偶数值产生1.这样,可以生成一束是1或2个随机整数,并计算cos(n*pi)

为N个元素
N = 10; %// Number of values in the array 

%// Generate random integers 
ind = randi(2, N, 1); 

%// Compute sequence via trigonometry 
out = cos(ind*pi); 
+0

方法#7是不能保证的大'N'工作。 cos(9e7 * pi)-1'不等于零。 –

+0

@MohsenNosratinia - 确实如此。但是,如果您看到生成的值的范围,则会给出1和2的随机整数...并且不会有大的“N”值。然而,有'N'值为1或2 ....因此'cos(pi)'和'cos(2 * pi)'已被很好地定义。请重新阅读代码并确保这是所描述的消息。如果没有,请告诉我如何改写它。 – rayryeng

+0

哦,没错。我错过了, –

3

一个衬里:

2*randi(2, 1, N) - 3 

或许更清晰

(-1).^randi(2, 1, N) 
+0

第二种方法很聪明。 – rayryeng

+0

第二种方法非常聪明! – yayaya