如何调整随机结果

时间:2012-08-16 16:40:55

标签: matlab

我在调整数字随机的结果时遇到问题,

jum_k = 14;
jum_b = 12;

result = randint(jum_k, jum_b, [0 2]);

因此对最终结果有约束。行中不应出现值“0”超过三次。

1 个答案:

答案 0 :(得分:1)

然后,随机条目非均匀地分布,具有未知权重,即每行零的数量可以是<= 3([0,1,2,3])。我会用这种方式解决它:在[1,2]中统一填充[m x n]矩阵,选择(随机)每行零,然后选择(随机)它们的位置。例如:

jum_k = 14;
jum_b = 12;

result = randi([1, 2], jum_k, jum_b);
for i = 1:jum_k
    nZeros = randi([0, 3]); % number of zeros (random)
    result(i, randi(jum_b, 1, nZeros)) = 0; % locations in line (random)
end;

如果每行需要确切数量的零,则可以相应地进行修改。

编辑(在对评论提出的问题进行澄清之后):为了容纳每行不超过3个零,例如: [1,0,0,0...2]您可以按元素填充矩阵并检查先前元素中的模式[0,0,0,0](保留先前值的缓冲区)。

result = nan(jum_k, jum_b); % intitialize
for i = 1:jum_k
    for j = 1:jum_b
        result(i, j) = randi([0, 2]); % assign value       
        if j>3 && ~all(result(i, j-3:j)) % check previous values
            result(i, j-randi([0, 3])) = randi([1, 2]); % randomly change one 
        end
    end
end

%% check/test that all lines have less 4 zeros in sequence
f = @strfind;
for i = 1:jum_k
    t(i) = isempty(f(result(i,:),[0 0 0 0]));
end
T = all(t); 

这不是最佳的(以MATLAB为单位),但会完成这项工作。