在MATLAB中创建元素数量有限的矩阵

在MATLAB中创建元素数量有限的矩阵,matlab,matrix,Matlab,Matrix,我想在MATLAB中创建一个12*3的矩阵,每行只有2个非零元素。我应该如何生成代码以获得所有可能的条件。非零元素可以采用1到2之间的任何整数。如果您希望所有可能的组合不重复0,重复1和2: % Number of integer with repetition. n = 2 % Generate all the possible combination of 1 and 2. [x1,x2] = meshgrid(1:n,1:n); M = [zeros(n^2,1),x1(:),x2(:)

我想在MATLAB中创建一个12*3的矩阵,每行只有2个非零元素。我应该如何生成代码以获得所有可能的条件。非零元素可以采用1到2之间的任何整数。

如果您希望所有可能的组合不重复0,重复1和2:

% Number of integer with repetition.
n = 2

% Generate all the possible combination of 1 and 2.
[x1,x2] = meshgrid(1:n,1:n);
M = [zeros(n^2,1),x1(:),x2(:)];

% We shift the 0 column n time.
M = cell2mat(arrayfun(@(x) circshift(M,x,2),0:n,'UniformOutput',0).');
结果:

M =

   0   1   1
   0   1   2
   0   2   1
   0   2   2
   1   0   1
   2   0   1
   1   0   2
   2   0   2
   1   1   0
   1   2   0
   2   1   0
   2   2   0

谢谢。如果24*4矩阵只需要两个非零元素(即1和2),该怎么办。这意味着将有一个重复的零。