如何在不重复行和列的情况下生成随机矩阵?
问题描述:
如何在不重复特定范围的行和列的情况下生成随机矩阵
How to generate random matrix without repetition in rows and cols with specific range
示例(3x3):范围1到3
2 1 3
3 2 1
1 3 2
示例(4x4):范围1到4
4 1 3 2
1 3 2 4
3 2 4 1
2 4 1 3
答
假设您要包含 1
和 n
%// Elements to be contained, but no zero allowed
a = [1 2 3 4];
%// all possible permutations and its size
n = numel(a);
%// initialization
output = zeros(1,n);
ii = 1;
while ii <= n;
%// random permuation of input vector
b = a(randperm(n));
%// concatenate with already found values
temp = [output; b];
%// check if the row chosen in this iteration already exists
if ~any( arrayfun(@(x) numel(unique(temp(:,x))) < ii+1, 1:n) )
%// if not, append
output = temp;
%// increase counter
ii = ii+1;
end
end
output = output(2:end,:) %// delete first row with zeros
这绝对不是最快的实现.我会很想见别人.计算时间成倍增加.但是7x7以下的所有内容都是可以承受的.
It definitely won't be the fastest implementation. I would be curios to see others. The computation time increases exponentially. But everything up to 7x7 is bearable.