【发布时间】:2013-06-22 17:34:23
【问题描述】:
我需要生成一个包含 1 和 0 的 K 列和 N 行的随机矩阵,这样:
a) 每一行都恰好包含 k 个。
b) 每一行都不同(组合学规定如果N > nchoosek(K, k) 将有nchoosek(K,k) 行)。
假设我想要 N = 10000(在所有可能的 nchoosek(K, k) = 27405 组合中),不同的 1×K 向量(带有 K = 30)包含 k 个(带有 k = 4)一个和 K - k 个零。
这段代码:
clear all; close
N=10000; K=30; k=4;
M=randi([0 1],N,K);
plot(sum(M,2)) % condition a) not satisfied
既不满足a)也不满足b)。
这段代码:
clear all; close;
N=10000;
NN=N; K=30; k=4;
tempM=zeros(NN,K);
for ii=1:NN
ttmodel=tempM(ii,:);
ttmodel(randsample(K,k,false))=1; %satisfies condition a)
tempM(ii,:)=ttmodel;
end
Check=bi2de(tempM); %from binary to decimal
[tresh1,ind,tresh2] = unique(Check);%drop the vectors that appear more than once in the matrix
M=tempM(ind,:); %and satisfies condition b)
plot(sum(M,2)) %verify that condition a) is satisfied
%Effective draws, Wanted draws, Number of possible combinations to draw from
[sum(sum(M,2)==k) N nchoosek(K,k) ]
满足条件 a) 和部分条件 b)。我说部分是因为除非 NN>>N,否则最终矩阵将包含少于 N 的行,每个行彼此不同。
有没有更好更快的方法(可能避免for循环和需要NN>>N)来解决问题?
【问题讨论】:
标签: matlab sparse-matrix