MATLAB爱好者论坛-LabFans.com

MATLAB爱好者论坛-LabFans.com (https://www.labfans.com/bbs/index.php)
-   资料存档 (https://www.labfans.com/bbs/forumdisplay.php?f=72)
-   -   生成矩阵的线性组合 (https://www.labfans.com/bbs/showthread.php?t=26276)

poster 2019-12-14 20:13

生成矩阵的线性组合
 
我要创建一个矩阵A [4x8],如下所示。

矩阵A的对角线始终为1 。 A11,A22,A33,A44 = 1

这个矩阵可以看作是两半,前半部分是前4列,后半部分是后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 前半部分的每一行可以有两个或三个-1:
[LIST][*]如果它有两个-1 ,则后半部分的相应行应有一个1[*]如果任何行具有三个-1 ,则矩阵的后半部分应具有两个1 。[/LIST]总体目标是使每一行的总和为0 。我需要生成像这样的矩阵的所有可能组合。

如果在每次迭代时都创建具有新组合的矩阵会更好,这样在使用它之后我可以丢弃它,否则存储所有组合会占用大量空间。有谁能够帮助我 ?

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



[B]回答:[/B]

这是一种可能的解决方案。如果暂时忽略对角线,则可以使用函数[URL="http://www.mathworks.com/help/techdoc/ref/kron.html"]KRON[/URL] , [URL="http://www.mathworks.com/help/techdoc/ref/repmat.html"]REPMAT[/URL] , [URL="http://www.mathworks.com/help/techdoc/ref/perms.html"]PERMS[/URL] , [URL="http://www.mathworks.com/help/techdoc/ref/unique.html"]UNIQUE[/URL] , [URL="http://www.mathworks.com/help/techdoc/ref/eye.html"]EYE[/URL]和[URL="http://www.mathworks.com/help/techdoc/ref/ones.html"]ONES[/URL]生成其他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 请注意,对于任何给定的行,这是18个可能的模式,因此矩阵A可以具有18 ^ 4 = 104,976个可能的行模式(有点)。您可以使用函数[URL="http://www.mathworks.com/help/techdoc/ref/ndgrid.html"]NDGRID[/URL] , [URL="http://www.mathworks.com/help/techdoc/ref/cat.html"]CAT[/URL]和[URL="http://www.mathworks.com/help/techdoc/ref/reshape.html"]RESHAPE[/URL]生成每个可能的4向行模式索引:

[indexSets{1:4}] = ndgrid(1:18); indexSets = reshape(cat(5,indexSets{:}),[],4); 并且indexSets将是一个104,976×4的矩阵,每行包含1到18之间(含1和18)的4个值的组合,以用作rowPatterns索引以生成唯一矩阵A现在,您可以遍历每组4向行模式索引,并使用函数[URL="http://www.mathworks.com/help/techdoc/ref/tril.html"]TRIL[/URL] , [URL="http://www.mathworks.com/help/techdoc/ref/triu.html"]TRIU[/URL] , [URL="http://www.mathworks.com/help/techdoc/ref/eye.html"]EYE[/URL]和[URL="http://www.mathworks.com/help/techdoc/ref/zeros.html"]ZEROS[/URL]生成矩阵A :

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

[url=https://stackoverflow.com/questions/4890768]更多&回答...[/url]


所有时间均为北京时间。现在的时间是 23:19

Powered by vBulletin
版权所有 ©2000 - 2025,Jelsoft Enterprises Ltd.