2013-03-29 68 views
0

我想在matlab中生成每個布爾矩陣作爲三維數組。在matlab中生成每個二進制n×m矩陣

例如:

mat(:,:,1) = [[1 0][0 1]] 
mat(:,:,2) = [[1 1][0 1]] 
... 

我的最終目標是產生一個給定尺寸的每一個三元矩陣。請記住,我知道矩陣的數量是指數,但我會用小數字。

回答

1

不知道以前的答案實際上是你想要的......用這種方法,我在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*nRows2^(nRows*nRows)矩陣其他任何東西。 ThatsAlottaNumbers。

0

其實答案很簡單。每個矩陣都是布爾型的,它可以按照任何給定順序讀取所有值時獲得的二進制數進行索引。

對於二元矩陣:let n是矩陣中元素的數量(n = rows * cols)。

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,可以很容易地推廣到任何基礎。