Labfans是一个针对大学生、工程师和科研工作者的技术社区。 | 论坛首页 | 联系我们(Contact Us) |
![]() |
|
![]() |
#1 |
高级会员
注册日期: 2019-11-21
帖子: 3,006
声望力: 66 ![]() |
![]()
我要创建一个矩阵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:
如果在每次迭代时都创建具有新组合的矩阵会更好,这样在使用它之后我可以丢弃它,否则存储所有组合会占用大量空间。有谁能够帮助我 ? 我想到的一种可能的解决方案是生成row1,row2,row3和row4的所有可能组合,并在每次迭代中创建一个矩阵。看起来可行吗? 回答: 这是一种可能的解决方案。如果暂时忽略对角线,则可以使用函数KRON , REPMAT , PERMS , UNIQUE , EYE和ONES生成其他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个可能的行模式(有点)。您可以使用函数NDGRID , CAT和RESHAPE生成每个可能的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向行模式索引,并使用函数TRIL , TRIU , EYE和ZEROS生成矩阵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 更多&回答... |
![]() |
![]() |