[英]How to find all possible combinations of a matrix with fixed components
Given a 3by2 matrix with constant values给定一个具有常量值的 3by2 矩阵
B = [b1 b1;b2 b2;b3 b3]
I need to make a code that would use the initial B matrix and place zeros progressively to any place of its current components.我需要编写一个代码,该代码将使用初始 B 矩阵并将零逐渐放置到其当前组件的任何位置。 This means that we need factorial(6) combinations.这意味着我们需要 factorial(6) 组合。 The first combination which would be of no use, is when we replace all components with 6 zeros:第一个没有用的组合是当我们用 6 个零替换所有组件时:
B_0 = [0 0;0 0;0 0]
The first useful output would be, placing 5 zeros in all places BUT the (1,1)第一个有用的输出是,在所有位置放置 5 个零,但 (1,1)
B_1 = [b1 0;0 0;0 0]
The second, would be placing zeros in all places but the (2,1):第二,将在除 (2,1) 之外的所有地方放置零:
B_2 = [0 0;b1 0;0 0]
so on for the third:依此类推第三个:
B_3 = [0 0;0 0;b1 0]
After finishing with placing all the combinations for 5 zeros, we start to add 4 zeros:完成 5 个零的所有组合后,我们开始添加 4 个零:
B_k = [b1 0;b2 0;0 0]
B_k+1 = [b1 0;0 0;b3 0]
etc. and then 3 zeros等等,然后是 3 个零
B_n = [b1 0;b2 0;b3 0]
B_n+1 = [b1 0;b2 0;0 b3]
etc.等等。
Until, we arrive to the last case of no zeros to be replaced which brings us to the initial matrix直到,我们到达没有零被替换的最后一种情况,这将我们带到了初始矩阵
B_6! = [b1 b1;b2 b2;b3 b3]
I made the assumption that there is a mistake in your question (according to my comment).我假设您的问题中有错误(根据我的评论)。 So there is only 2^6 = 64 possible combinations.所以只有 2^6 = 64 种可能的组合。
In this case you can use:在这种情况下,您可以使用:
m = 6 %vector length
[y{1:m}] = ndgrid(0:1); %all combination of 0 and 1 with m possible permutations
y = reshape(cat(m+1,y{:}),[],m);
res = y.*[1 1 2 2 3 3] %get the result
%reshape and permute
res = permute(reshape(res.',2,3,64),[2,1,3])
I've added a new dimension instead of creating 64 new variables (which is not the way to go).我添加了一个新维度,而不是创建 64 个新变量(这不是可行的方法)。
result (before adding a new dimension and reshaping):结果(在添加新维度和重塑之前):
res =
0 0 0 0 0 0
1 0 0 0 0 0
0 1 0 0 0 0
1 1 0 0 0 0
0 0 2 0 0 0
1 0 2 0 0 0
0 1 2 0 0 0
1 1 2 0 0 0
0 0 0 2 0 0
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.