在Matlab中生成每个二进制n x m矩阵 [英] Generate every binary n x m matrix in matlab

查看:428
本文介绍了在Matlab中生成每个二进制n x m矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在matlab中将每个布尔矩阵生成为3维数组.

I'd like to generate every boolean matrix in matlab as a 3-dimensional array.

例如:

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

我的最终目标是生成给定大小的每个三进制矩阵. 请记住,我知道矩阵的数量是指数的,但是我将使用较小的数字.

My final goal is to generate every trinary matrix of a given size. Keep in mind that I know that the number of matrices is exponential, but I'll use small numbers.

推荐答案

不确定先前的答案是否确实满足您的要求...通过该方法,我在array2D中得到了多个相同的条目.这是向量化的(我相信)正确的解决方案:

Not sure that the previous answer actually does what you want... With that method, I get multiple entries in array2D that are the same. Here is a vectorised and (I believe) correct solution:

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.

Note that for anything other than small numbers of nRows you will run out of memory pretty quickly, because you're generating 2^(nRows*nRows) matrices of size nRows*nRows. ThatsAlottaNumbers.

这篇关于在Matlab中生成每个二进制n x m矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆