生成矩阵的线性组合

0x0*_*0x0 2 matlab matrix

我想创建一个矩阵A [4x8],如下所示.

矩阵A总是具有1对角线.A11,A22,A33,A44 = 1

这个矩阵可以被认为是两半,前半部分是前4列,后半部分是第二列,如下所示:

        1 -1 -1 -1   1 0 0 1
  A =  -1  1 -1  0   0 1 0 0
       -1 -1  1  0   1 0 0 0 
       -1 -1 -1  1   1 1 0 0
Run Code Online (Sandbox Code Playgroud)

前半部分的每行可以有两个或三个-1:

  • 如果它有两个-1,则后半部分中的相应行应该有一个1
  • 如果任何行有三个-1,则矩阵的后半部分应该有两个1.

总体目标是得到每一行的总和0.我需要生成像这样的矩阵的所有可能组合.

如果在每次迭代中创建具有新组合的矩阵将更好,以便在使用它之后我可以丢弃它或者存储所有组合是非常空间密集的.有谁能够帮我 ?

我能想到的一个可能的解决方案是生成row1,row2,row3和row4的所有可能组合,并在每次迭代中创建一个矩阵.这看起来可行吗?

gno*_*ice 5

这是一种可能的解决方案.如果暂时忽略对角线,可以使用KRON,REPMAT,PERMS,UNIQUE,EYEONES函数为其他7个值生成所有可能的模式:

>> rowPatterns = [kron(eye(3)-1,ones(4,1)) ...      %# For 2 out of 3 as -1
                  repmat(eye(4),3,1); ...           %# For 1 out of 4 as 1
                  repmat([-1 -1 -1],6,1) ...        %# For 3 out of 3 as -1
                  unique(perms([1 1 0 0]),'rows')]  %# For 2 out of 4 as 1

rowPatterns =

     0    -1    -1     1     0     0     0
     0    -1    -1     0     1     0     0
     0    -1    -1     0     0     1     0
     0    -1    -1     0     0     0     1
    -1     0    -1     1     0     0     0
    -1     0    -1     0     1     0     0
    -1     0    -1     0     0     1     0
    -1     0    -1     0     0     0     1
    -1    -1     0     1     0     0     0
    -1    -1     0     0     1     0     0
    -1    -1     0     0     0     1     0
    -1    -1     0     0     0     0     1
    -1    -1    -1     0     0     1     1
    -1    -1    -1     0     1     0     1
    -1    -1    -1     0     1     1     0
    -1    -1    -1     1     0     0     1
    -1    -1    -1     1     0     1     0
    -1    -1    -1     1     1     0     0
Run Code Online (Sandbox Code Playgroud)

请注意,对于任何给定的行,这是18种可能的模式,因此您的矩阵A可以具有18 ^ 4 = 104,976种可能的行模式(相当多).您可以使用NDGRID,CATRESHAPE函数生成每个可能的4 行行模式索引:

[indexSets{1:4}] = ndgrid(1:18);
indexSets = reshape(cat(5,indexSets{:}),[],4);
Run Code Online (Sandbox Code Playgroud)

并且indexSets将是104,976乘4的矩阵,每行包含1和18之间的4个值的一个组合,包括在内,以用作rowPatterns生成唯一矩阵的索引A.现在,您可以循环遍历每组4向行模式索引,并A使用函数TRIL,TRIU,EYEZEROS生成矩阵:

for iPattern = 1:104976
  A = rowPatterns(indexSets(iPattern,:),:);  %# Get the selected row patterns
  A = [tril(A,-1) zeros(4,1)] + ...          %# Separate the 7-by-4 matrix into
      [zeros(4,1) triu(A)] + ...             %#   lower and upper parts so you
      [eye(4) zeros(4)];                     %#   can insert the diagonal ones
  %# Store A in a variable or perform some computation with it here
end
Run Code Online (Sandbox Code Playgroud)