在matlab中生成每个二进制nxm矩阵
我想在matlab中生成每个布尔矩阵作为三维数组 例如:在matlab中生成每个二进制nxm矩阵,matlab,matrix,binary,Matlab,Matrix,Binary,我想在matlab中生成每个布尔矩阵作为三维数组 例如: mat(:,:,1) = [[1 0][0 1]] mat(:,:,2) = [[1 1][0 1]] ... 我的最终目标是生成给定大小的每个三元矩阵。 请记住,我知道矩阵的数量是指数的,但我将使用较小的数字。事实上,答案非常简单。每一个矩阵都是布尔型的,它可以通过读取任意给定顺序的所有值时获得的二进制数来索引 对于二进制矩阵:设n为矩阵中的元素数(n=行*列) 通过将dec2bin更改为dec2base并将2^n更改为(yourba
mat(:,:,1) = [[1 0][0 1]]
mat(:,:,2) = [[1 1][0 1]]
...
我的最终目标是生成给定大小的每个三元矩阵。
请记住,我知道矩阵的数量是指数的,但我将使用较小的数字。事实上,答案非常简单。每一个矩阵都是布尔型的,它可以通过读取任意给定顺序的所有值时获得的二进制数来索引 对于二进制矩阵:设n为矩阵中的元素数(n=行*列)
通过将dec2bin更改为dec2base并将2^n更改为(yourbase)^n,这可以很容易地推广到任何基数。不确定前面的答案是否真的符合您的要求。。。通过该方法,我在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)
请注意,除了少量的nRows
之外,您将很快耗尽内存,因为您正在生成大小为nRows*nRows
的2^(nRows*nRows)
矩阵。那是一个月前的事
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)