【问题标题】:Matlab - Shuffling matrix values based on some conditionsMatlab - 基于某些条件的洗牌矩阵值
【发布时间】:2016-08-09 10:46:52
【问题描述】:

我有以下两个矩阵,它们是过程的输出。矩阵的大小可能会改变,但两个矩阵的大小始终相同:size(TwoHopMat_1) == size(Final_matrix)

示例:

TwoHopMat_1 =

     0     0     0     0     1
     0     0     1     1     0
     0     1     0     1     0
     0     1     1     0     0
     1     0     0     0     0


Final_matrix =

 1     0     0     0     1
 1     0     0     0     1
 1     0     0     0     1
 1     1     0     0     0
 1     0     0     0     1

现在我需要对 final_matrix 进行洗牌,使我在洗牌后满足以下条件:

  1. 每列至少应有一个 1s
  2. 如果我在 TwoHopMat_1 的特定位置有 1,那么在洗牌后该特定位置不应该有 1。

即使我们给出大小为 100x100 的矩阵,条件也应该有效。

【问题讨论】:

  • 您需要在结果矩阵中包含与 Final_matrix 中相同数量的“1”?
  • 是的,而且传播得很好

标签: matlab matrix


【解决方案1】:

第一步:设置结果矩阵每一列的一个元素,即Final_matrix中不为1的元素为1

第二步:然后将剩余的随机插入到Final_matrix中不为1且在第一步结果中不为1的结果矩阵的位置

TwoHopMat_1=[...
     0     0     0     0     1
     0     0     1     1     0
     0     1     0     1     0
     0     1     1     0     0
     1     0     0     0     0];
Final_matrix=[...
     1     0     0     0     1
     1     0     0     0     1
     1     0     0     0     1
     1     1     0     0     0
     1     0     0     0     1];
[row col] = size(Final_matrix);
result = zeros(row ,col);
%condition 1 & 2 :
notTwoHop = ~TwoHopMat_1;
s= sum(notTwoHop,1);
c= [0 cumsum(s(1:end - 1))];
f= find(notTwoHop);
r = floor(rand(1, col) .* s) + 1;
i = c + r;
result(f(i)) = 1;
%insert remaining ones randomly into the result
f= find(~(result | TwoHopMat_1));
i = randperm(numel(f), sum(Final_matrix(:))-col);
result(f(i)) =1

【讨论】:

    【解决方案2】:

    一个可能的解决方案:

    function [result_matrix] = shuffle_matrix(TwoHopMat_1, Final_matrix)
    
      % Condition number 2
      ones_mat = ones(size(TwoHopMat_1));
      temp_mat = abs(TwoHopMat_1 - ones_mat);
    
      % Condition number 1
      ones_to_remove = abs(sum(sum(temp_mat)) - sum(sum(Final_matrix)));
      while ones_to_remove > 0
        % Random matrix entry
        i = floor((size(Final_matrix, 1) * rand())) + 1;
        j = floor((size(Final_matrix, 2) * rand())) + 1;
    
        if temp_mat(i,j) == 1
          temp_mat(i,j) = 0;
          ones_to_remove = ones_to_remove - 1;
        end    
      end
      result_matrix = temp_mat;
    end
    

    注意:此解决方案使用蛮力。

    【讨论】:

    • 非常感谢它的工作原理,但是我在 15 次中有 2 次在列中得到全零。
    猜你喜欢
    • 2023-03-16
    • 1970-01-01
    • 1970-01-01
    • 2012-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-02
    相关资源
    最近更新 更多