如何在不重复行和列的情况下生成随机矩阵? [英] How to generate random matrix without repetition in rows and cols?
本文介绍了如何在不重复行和列的情况下生成随机矩阵?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在不重复特定范围的行和列的情况下生成随机矩阵
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.
这篇关于如何在不重复行和列的情况下生成随机矩阵?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文