在某些地方放 1

Putting 1's in certain places

我有 2 个矩阵

  Matrix A = [7 3 5 2 8 4 1 6 9;
              5 2 6 1 4 3 9 7 8;
              9 1 4 5 2 6 3 6 7;
              4 8 1 6 3 7 2 9 5;
              6 1 7 2 8 4 5 9 3]

 Matrix B =  [1 0 0 0 0 0 0 0 0;
              0 1 1 0 0 0 0 0 0;
              0 0 0 0 0 0 0 1 0;
              0 0 0 1 0 1 0 0 0;
              0 0 0 0 0 0 0 0 1]

矩阵 A 和 B 已经定义。

这里每列不能超过 1 我想做的是如果当我对矩阵 B 求和时如果我在其中找到 0 我必须在零的位置添加 1 但在某些情况下地方。在每一行中,1 必须放在特定的组中。例如,如果 1 被放置在第 1 列,那么它也可以被放置在第 2 列或第 3 列。它不能放在其他任何地方。如果在另一行中它被放置在第 5 列,则它只能被放置在第 4 或 6 列,依此类推。好像是3人一组。每3列在一起。

更清楚:

这里矩阵B的和是[1 1 1 1 0 1 0 1 1]。这里的零放在第 5 列和第 7 列中,我想添加 1,记住 1 将放置在矩阵中的位置。因此,在此示例中,第 5 列的 1 只能放置在第 4 行中,因为该行中的 1 放置在第 4 列和第 6 列中。第 7 列的 1 可以放置在第 5 行或第 3 行中。如果我们可以选择2 行然后 1 将被放置在矩阵 A 的较高数字的位置。 1 必须分组;第 1、2 和 3 列在一起,第 4、5 和 6 列在一起,第 7、8 和 9 列在一起。所以如果 1 被放置在组的第 1 列,那么它就不能被放置在任何其他地方。

让我简化一下,如果我们有这样的数组 [0 0 0 0 0 0 0 1 1] 这个数组有 3 个类别,第 1,2 和 3 列是第一个类别,第 4,5 和 6 列是第二类等等。在这里我想放置一个 1,这样第 3 类就不会有零元素。这是我想简单做的,但是有一个包含所有类别的整个矩阵。

所以这里的输出将是 =

     [1 0 0 0 0 0 0 0 0;
      0 1 1 0 0 0 0 0 0;
      0 0 0 0 0 0 0 1 0;
      0 0 0 1 1 1 0 0 0;
      0 0 0 0 0 0 1 0 1]

已尝试此代码,但它没有提供所需的输出,因为 1 被放置在第一行而不是它必须位于的位置(它应该位于的类别)。

sum_cols_B = sum(B);               % Sum of Matrix B (dim 1)      
[~, idx] = find(sum_cols_B == 0);  % Get indices where sum == 0

% Using loop to go through the indices (where sum = 0)          
for ii = idx  
B(1,ii) = 1;                       % Insert 1 in the first position of that 
end                                % column in Matrix B

还有不明白的再问我吧!

B =  [1 0 0 0 0 0 0 0 0;...
      0 1 1 0 0 0 0 0 0;...
      0 0 0 0 0 0 0 1 0;...
      0 0 0 1 0 1 0 0 0;...
      0 0 0 0 0 0 0 0 1];          % Matrix - using this as an example

sum_cols_B = sum(B);               % Sum of Matrix B (dim 1)      
[~, idx] = find(sum_cols_B == 0);  % Get indices where sum == 0

% Using loop to go through the indices (where sum = 0)          
for ii = idx  
B(1,ii) = 1;                       % Insert 1 in the first position of that 
end                                % column in Matrix B

这是一个更新的循环,它将添加缺失的 1:

sum_cols_B = sum(B);
[~, idx] = find(sum_cols_B == 0);

group_size = 3;
for ii = idx 
   % Calculate the starting column of the group for column ii
   % There are (ii-1)/group_size groups
   % Add 1 for 1-based indexing
   group_start = floor((ii-1)/group_size)*group_size + 1;

   % Determine which rows in the current group have nonzero values
   group_mask = sum(B(:,group_start:group_start+group_size-1), 2) > 0;

   % Find the row number of the max in A column ii corresponding to mask
   [~,rownum] = max(A(:,ii).*group_mask);

   % The value in column ii of B should have a 1 inserted
   % at the row containing the max in A
   B(rownum,ii) = 1;
end

上面 B 的结果是:

B =

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