New*_*ent 1 matlab permutation matrix
我需要为一个矩阵创建所有可能的置换矩阵,其中每个置换矩阵的每一列和每行只包含一个 1,而在所有其他地方都包含一个 0。
例如,下面的示例(1)中是 2x2 矩阵的所有可能的置换矩阵,(2)中的示例是 3x3 矩阵的所有可能的置换矩阵,依此类推
那么如何在 MATLAB 中获取矩阵 NxN 的这些矩阵并将它们存储到一个三维矩阵中呢?
这是我的解决方案,使用隐式扩展(使用 Octave 5.2.0 和 MATLAB Online 测试):
n = 3;
% Get all permutations of length n
p = perms(1:n);
% Number of permutations
n_p = size(p, 1);
% Set up indices, where to set elements to 1
p = p + (0:n:n^2-1) + (0:n^2:n^2*n_p-1).';
% Set up indices, where to set elements to 1 (for MATLAB R2016a and before)
%p = bsxfun(@plus, bsxfun(@plus, p, (0:n:n^2-1)), (0:n^2:n^2*n_p-1).');
% Initialize 3-dimensional matrix
a = zeros(n, n, n_p);
% Set proper elements to 1
a(p) = 1
Run Code Online (Sandbox Code Playgroud)
的输出n = 3:
a =
ans(:,:,1) =
0 0 1
0 1 0
1 0 0
ans(:,:,2) =
0 1 0
0 0 1
1 0 0
ans(:,:,3) =
0 0 1
1 0 0
0 1 0
ans(:,:,4) =
0 1 0
1 0 0
0 0 1
ans(:,:,5) =
1 0 0
0 0 1
0 1 0
ans(:,:,6) =
1 0 0
0 1 0
0 0 1
Run Code Online (Sandbox Code Playgroud)