生成所有可能的整数数组

Jac*_*ack 3 arrays matlab permutation

我想生成给定长度的所有可能的整数数组,L最大元素大小M.

最小元素大小为1.

如果M = 3,和L = 2,输出将如下:

[1,1]
[1,2]
[1,3]
[2,1]
[2,2]
[2,3]
[3,1]
[3,2]
[3,3]
Run Code Online (Sandbox Code Playgroud)

M^L不同的组合,所以我猜Matlab代码看起来像这样:

function [arrays] = allArrays(M,L)
  for i = 1:(M^L)
    arrays(i) = % Something here that translates i to the desired array.
  end
end
Run Code Online (Sandbox Code Playgroud)

我不确定在循环中间应该去做什么,任何帮助都会非常感激!

Oli*_*Oli 7

你应该使用ndgrid:

[y x]=ndgrid(1:3,1:3);
resu=[y(:) x(:)];
Run Code Online (Sandbox Code Playgroud)

如果你想给予ML作为输入,你应该做以下技巧:

arg=repmat((1:M)',1,L);
arg=mat2cell(arg,M,ones(1,L));
resu=cell(1,L);
[resu{:}]=ndgrid(arg{:});
resu=cell2mat(cellfun(@(x) x(:), resu,'UniformOutput',0));
Run Code Online (Sandbox Code Playgroud)

结果:

 resu =  
     1     1
     2     1
     3     1
     1     2
     2     2
     3     2
     1     3
     2     3
     3     3
Run Code Online (Sandbox Code Playgroud)