2015-10-26 39 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