在每次迭代中,我想将1随机添加到二进制矢量中, 让我们说
iteration = 1,
k = [0 0 0 0 0 0 0 0 0 0]
iteration = 2,
k = [0 0 0 0 1 0 0 0 0 0]
iteration = 3,
k = [0 0 1 0 0 0 0 1 0 0]
,最多可达length(find(k)) = 5;
我在想 for loop ,但我不知道如何开始。
答案 0 :(得分:1)
我甚至不会使用循环。我会生成索引的随机排列,这些索引从1到k
长度的向量中进行采样,无需替换然后将这些位置设置为1. randperm
适合任务很好:
N = 10; %// Length 10 vector
num_vals = 5; %// 5 values to populate
ind = randperm(N, num_vals); %// Generate a vector from 1 to N and sample num_vals values from this vector
k = zeros(1, N); %// Initialize output vector k to zero
k(ind) = 1; %// Set the right values to 1
以下是我运行此代码几次时的一些示例运行:
k =
0 0 1 1 0 1 1 0 0 1
k =
1 0 0 0 1 0 1 1 0 1
k =
1 0 0 0 1 0 1 1 0 1
k =
0 1 1 1 0 0 1 0 0 1
但是,如果您坚持使用循环,则可以生成从1到所需长度的向量,随机选择此向量中的索引,然后从向量中移除此值。然后,您可以使用此索引设置输出的位置:
N = 10; %// Length 10 vector
num_vals = 5; %// 5 values to populate
vec = 1 : N; %// Generate vector from 1 up to N
k = zeros(1, N); %// Initialize output k
%// Repeat the following for as many times as num_vals
for idx = 1 : num_vals
%// Obtain a value from the vector
ind = vec(randi(numel(vec), 1));
%// Remove from the vector
vec(ind) = [];
%// Set location in output to 1
k(ind) = 1;
end
上面的代码仍然会给你带来理想的效果,但我认为效率较低。
答案 1 :(得分:1)
如果拥有中间向量(具有1,2,... 4的那些)以及最后一个向量很重要,则可以生成随机排列,并且在您的示例中,使用前5个索引。一时间:
n = 9; %// number of elements in vector
m = 5; %// max number of 1's in vector
k = zeros(1, n);
disp(k); %// output vector of all 0's
idx = randperm(n);
for p = 1:m
k(idx(p)) = 1;
disp(k);
end
这是一个示例运行:
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 1
1 0 0 0 0 0 0 0 1
1 0 0 1 0 0 0 0 1
1 0 0 1 1 0 0 0 1
1 1 0 1 1 0 0 0 1