【问题标题】:How to balance unique values in an array Matlab如何平衡数组Matlab中的唯一值
【发布时间】:2020-10-09 07:06:57
【问题描述】:

我有一个向量

Y = [1 1 0 0 0 1 1 0 1 0 1 1 1 0 0 0 1 1 0 0 0 0 1 0 1 0 1 0 1 1 1 0 0 0 1 0 0 0]

1 出现 17 次

0 出现 21 次

如何随机删除 0,使两个值的数量相等,例如 1(17 次)和 0(17 次)?

这也应该适用于更大的矩阵。

【问题讨论】:

    标签: arrays matlab matrix random indexing


    【解决方案1】:

    从你的例子开始

    Y = [1 1 0 0 0 1 1 0 1 0 1 1 1 0 0 0 1 1 0 0 0 0 1 0 1 0 1 0 1 1 1 0 0 0 1 0 0 0]
    

    您可以执行以下操作:

    % Get the indices of the value which is more common (`0` here)
    zeroIdx = find(~Y); % equivalent to find(Y==0)
    % Get random indices to remove
    remIdx = randperm(nnz(~Y), nnz(~Y) - nnz(Y));
    % Remove elements
    Y(zeroIdx(remIdx)) = [];
    

    你可以结合最后两行,但我认为它会不太清楚。

    randperm 行正在选择要从 1 到零数之间的随机索引中删除的正确元素数。

    【讨论】:

      【解决方案2】:

      如果数据只能有两个值

      假定值为01。最常见的值被随机删除以使其计数相等:

      Y = [1 1 0 0 0 1 1 0 1 0 1 1 1 0 0 0 1 1 0 0 0 0 1 0 1 0 1 0 1 1 1 0 0 0 1 0 0 0]; % data
      ind0 = find(Y==0); % indices of zeros
      ind1 = find(Y==1); % indices of ones
      t(1,1:numel(ind0)) = ind0(randperm(numel(ind0))); % random permutation of indices of zeros
      t(2,1:numel(ind1)) = ind1(randperm(numel(ind1))); % same for ones. Pads shorter row with 0
      t = t(:, all(t,1)); % keep only columns that don't have padding
      result = Y(sort(t(:))); % linearize, sort and use those indices into the data
      

      多于两个值的泛化

      值是任意的。除了最不常见的值外,所有值都被随机删除以使其计数相等:

      Y = [0 1 2 0 2 1 1 2 0 2 1 2 2 0 0]; % data
      vals = [0 1 2]; % or use vals = unique(Y), but absent values will not be detected
      t = [];
      for k = 1:numel(vals) % loop over values
          ind_k = find(Y==vals(k));
          t(k, 1:numel(ind_k)) = ind_k(randperm(numel(ind_k)));
      end
      t = t(:, all(t,1));
      result = Y(sort(t(:)));
      

      【讨论】:

        猜你喜欢
        • 2014-11-03
        • 2014-04-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-12-12
        • 2014-11-30
        • 2013-08-31
        • 2018-03-09
        相关资源
        最近更新 更多