如何通过另一个向量置换向量的元素以获得置换矩阵

时间:2018-02-24 16:33:13

标签: matlab

我想通过另一个向量元素获得一个向量元素的所有可能排列。例如,一个矢量是A = [0 0 0 0]而另一个是B = [1 1]。我想用A替换A的元素来获得像这样的矩阵中的所有排列[1 1 0 0; 1 0 1 0; 1 0 0 1; 0 1 1 0; 0 1 0 1; 0 0 1 1]。实数A的长度很大,我应该能够选择B_max的长度并获得A的所有排列,其中B = [1],[1 1],[1 1 1],...,B_max。

非常感谢

1 个答案:

答案 0 :(得分:0)

实际上,由于AB总是分别定义为零的向量和1的向量,因此这个计算比你想象的要容易得多。您应该尊重的唯一约束是B,它们不是空的,它的元素不能大于或等于A中的元素数...因为在该阈值之后A将成为一个向量,并计算其排列只会浪费CPU周期。

这是脚本的核心功能,它在给定目标向量0的情况下创建1X的唯一排列:

function p = uperms(X)
    n = numel(X);
    k = sum(X);
    c = nchoosek(1:n,k);
    m = size(c,1);

    p = zeros(m,n);
    p(repmat((1-m:0)',1,k) + m*c) = 1;
end

这是完整的代码:

clear();
clc();

% Define the main parameter: the number of elements in A...
A_len = 4;

% Compute the elements of B accordingly...
B_len = A_len - 1;
B_seq = 1:B_len;

% Compute the possible mixtures of A and B...
X = tril(ones(A_len));
X = X(B_seq,:);

% Compute the unique permutations...
p = [];

for i = B_seq
    p = [p; uperms(X(i,:).')];
end

A_len = 4的输出:

p =
     1     0     0     0
     0     1     0     0
     0     0     1     0
     0     0     0     1
     1     1     0     0
     1     0     1     0
     1     0     0     1
     0     1     1     0
     0     1     0     1
     0     0     1     1
     1     1     1     0
     1     1     0     1
     1     0     1     1
     0     1     1     1
相关问题