matlab のすべてのブール行列を 3 次元配列として生成したいと思います。
例えば:
mat(:,:,1) = [[1 0][0 1]]
mat(:,:,2) = [[1 1][0 1]]
...
私の最終的な目標は、指定されたサイズのすべての 3 値行列を生成することです。行列の数が指数関数的であることはわかっていますが、小さい数を使用することに注意してください。
前の答えが実際にあなたが望むことをするかどうかはわかりません...その方法では、array2Dに同じエントリが複数取得されます。ベクトル化された(私が信じている)正しい解決策は次のとおりです。
clear all;
nRows = 2;
nCols = nRows; % Only works for square matrices
% Generate matrix of all binary numbers that fit in nCols
max2Pow = nCols;
maxNum = 2 ^ max2Pow - 1;
allBinCols = bsxfun(@bitand, (0:maxNum)', 2.^((max2Pow-1):-1:0)) > 0;
% Get the indices of the rows in this matrix required for each output
% binary matrix
N = size(allBinCols, 1);
A = repmat({1:N}, nCols, 1);
[B{1:nCols}] = ndgrid(A{:});
rowInds = reshape(cat(3, B{:}), [], nCols)';
% Get the appropriate rows and reshape to a 3D array of right size
nMats = size(rowInds, 2);
binMats = reshape(allBinCols(rowInds(:), :)', nRows, nCols, nMats)
size の行列を生成しているため、少数以外のnRows
場合はすぐにメモリ不足になることに注意してください。それはアロッタナンバーズです。2^(nRows*nRows)
nRows*nRows
実際、答えはかなり簡単です。各マトリックスはブール値であり、すべての値を任意の順序で読み取ったときに取得された 2 進数によってインデックスを付けることができます。
バイナリ マトリックスの場合: n をマトリックス内の要素の数とします (n = 行 * 列)。
for d=0:(2^n-1)
%Convert binary to decimal string
str = dec2bin(d);
%Convert string to array
array1D = str - '0';
array1D = [array1D zeros(1, n-length(array1D))];
%Reshape
array2D(:,:,d+1) = reshape(array1D, rows, cols);
end
これは、dec2bin を dec2base に変更し、2^n を (yourbase)^n に変更することで、任意のベースに非常に簡単に一般化できます。