在MATLAB中随机选择具有权重的矩阵行

时间:2014-07-23 03:00:17

标签: matlab

说我想从矩阵m

中随机选择3行
m = [1 2 1; 1 1 1; 1 1 1; 2 1 1; 2 2 1; 1 1 1; 1 1 1; 2 1 1];
sample = m(randsample(1:length(m),3),:)

但是,我想随机选择有权重的行。所以我需要一个与m的每一行对应的向量。我想对每一行应用加权,具体取决于每行中出现的12的数量(或比率)。

也许是这样的?

w1 = 0.6;                 %weight of 1
w2 = 0.4;                 %weight of 2
w = m;
w(w == 1) = w1;
w(w == 2) = w2;
w = (sum(w,2))*0.1        %vector of weights

但这是错误的:

sample = m(randsample(1:length(m),2),:,true,w)

请帮忙。

1 个答案:

答案 0 :(得分:2)

保持代码,我认为您需要对权重进行标准化,然后根据使用标准化权重从randsample计算的随机样本选择行。 因此,您的代码需要进行以下更改 -

w = sum(w,2)./sum(sum(w,2)) %// Normalize weights
sample = m(randsample([1:size(m,1)], 3, true, w) ,:)

或者,如果我可以重新开始并希望使代码简洁,我可以这样做 -

%// Inputs
m = [1 2 1; 1 1 1; 1 1 1; 2 1 1; 2 2 1; 1 1 1; 1 1 1; 2 1 1]
w1 = 0.6;                 %// weight of 1
w2 = 0.4;                 %// weight of 2

%// Scale each row of w according to the weights assigned for 1 and 2.
%// Thus, we will have weights for each row
sum_12wts = sum(w1.*(m==1),2) + sum(w2.*(m==2),2)

%// Normalize the weights, so that they add upto 1, as needed for use with
%// randsample
norm_weights = sum_12wts./sum(sum_12wts)

%// Get 3 random row indices from m using randsample based on normalized weights
row_ind = randsample([1:size(m,1)], 3, true, norm_weights) 

%// Index into m to get the desired output
out = m(row_ind,:)