【发布时间】:2015-10-26 05:07:37
【问题描述】:
我想知道如何随机生成-1或1的序列。
例如:
[1 1 -1 -1] or
[-1 1 -1 1 1 1 1 -1 ] or
[-1 1 1 -1 1 -1 -1] are what I expect.
但[-1 0 1 -1 -1] 或[2 1 -1 -1 1 1] 不是我想要的。
【问题讨论】:
我想知道如何随机生成-1或1的序列。
例如:
[1 1 -1 -1] or
[-1 1 -1 1 1 1 1 -1 ] or
[-1 1 1 -1 1 -1 -1] are what I expect.
但[-1 0 1 -1 -1] 或[2 1 -1 -1 1 1] 不是我想要的。
【问题讨论】:
N 个元素的一个衬里:
2*randi(2, 1, N) - 3
或者更清楚
(-1).^randi(2, 1, N)
【讨论】:
有几种方法可以做到这一点。
您可以创建一个包含[-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);
还可以生成随机均匀分布的浮点值,大于0.5的可以设置为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;
您可以使用cos(n*pi) 可以给出1 或-1 的事实,这取决于n 的值,只要n 是一个整数。奇数产生-1,偶数产生1。因此,您可以生成一堆1或2的随机整数,并计算cos(n*pi):
N = 10; %// Number of values in the array
%// Generate random integers
ind = randi(2, N, 1);
%// Compute sequence via trigonometry
out = cos(ind*pi);
【讨论】:
N。 cos(9e7*pi)-1 不等于零。
N 的大值。但是,N 的值是 1 或 2....因此,cos(pi) 和 cos(2*pi) 定义明确。请重新阅读代码并确保这是所描绘的信息。如果不是,请告诉我如何改写它。