生成相等数量的随机整数以响应 Matlab 中的先前输入

Generating an equal number of random integers in response to a previous input in Matlab

我正在尝试在 matlab 中创建一个随机数矩阵。但是,我对其中一些逻辑有点挣扎。我想要的是:

我需要它遍历一个预定义的随机矩阵(2 行,n 列),其中 50% 是 1,50% 是 0(我已经可以做到这部分)。每次遇到 1 时,它都应该进入另一个循环,将 1、2、3 或 4 放在第二行的相应位置。但是(这是我正在努力解决的部分)我需要它在第二行中有相同数量的 1、2、3 和 4。例如:

矩阵n = [0, 1, 0, 1, 1, 1, 0, 0; 0,0,0,0,0,0,0,0] 应该 运行 通过脚本并生成如下内容: n = [0, 1, 0, 1, 1, 1, 0, 0; 0, 1, 0, 3, 2, 4, 0, 0]

这是我目前拥有的:

function pureToneTimer
ptpschedule = [0, 1, 0, 1, 1, 1, 0, 0; 0, 0, 0, 0, 0 , 0, 0, 0]
a = 0;
b = 0;
c = 0;
d = 0;
x = length(ptpschedule)/4
for n = 1:length(ptpschedule) 
    if ptpschedule(1,n) == 1
        while a < x && b < x && c < x && d < x
        i = randi(4)
        ptpschedule(2,n) = i;
        switch i
            case 1
                a = a + 1;
            case 2
                b = b + 1;
            case 3
                c = c + 1;
            case 4
                d = d + 1;
        end
        end
    end
end
assignin('caller', 'ptpschedule', ptpschedule)
end

抱歉,如果这是一个非常微不足道的问题。我只是在努力解决这个问题!

谢谢,

马丁

这就是你想要的:

V = 4; %// number of values you want. 4 in your example
ind = ptpschedule(1,:)>0; %// logical index of positive values in the first row
n = nnz(ind);
vals = mod(0:n-1, V)+1; %// values to be randomly thrown in.
    %// This guarantees the same number of each value if n is a multiple of V
ptpschedule(2,ind) = vals(randperm(n)); %// fill values in second row in random order
  • 如果第一行中 1 的数量是 V 的倍数,这将生成每个值 12 , ... V第二行相同次数

  • 否则,第二行中的某些值将比其他值出现一次。

示例:

ptpschedule = [0, 1, 0, 1, 1, 1, 0, 0
               0, 0, 0, 0, 0, 0, 0, 0];
V = 4;

生产

ptpschedule =
     0     1     0     1     1     1     0     0
     0     3     0     4     2     1     0     0