我在 MATLAB
中有一个元胞数组,如下所示,第一列是用户
ID 列表:
A = { 'U2', 'T13', 'A52';
'U2', 'T15', 'A52';
'U2', 'T18', 'A52';
'U2', 'T17', 'A995';
'U4', 'T18', 'A53';
'U4', 'T13', 'A64';
'U4', 'T18', 'A64';
....
}
我还有一个元胞数组 B
包含 user
的唯一 ID,如下所示:
B = {'U2', 'U4'}
我的目标是尝试为每个用户
随机选择两个样本。假设每个用户
在B
中至少有两个样本。
一个示例是 C
,如下所示:
C = { 'U2', 'T13', 'A52';
'U2', 'T18', 'A52';
'U4', 'T13', 'A64';
'U4', 'T18', 'A64';
...
}
如何生成这些样本?
最佳答案
以下代码应该会产生您正在寻找的内容:
A = {
'U2', 'T13', 'A52';
'U2', 'T15', 'A52';
'U2', 'T18', 'A52';
'U2', 'T17', 'A995';
'U4', 'T18', 'A53';
'U4', 'T13', 'A64';
'U4', 'T18', 'A64';
'U7', 'T14', 'A44';
'U7', 'T14', 'A27';
'U7', 'T18', 'A27';
'U7', 'T13', 'A341';
'U7', 'T11', 'A111';
'U8', 'T17', 'A39';
'U8', 'T15', 'A58'
};
% Find the unique user identifiers...
B = unique(A(:,1));
B_len = numel(B);
% Preallocate a cell array to store the results...
R = cell(B_len*2,size(A,2));
R_off = 1;
% Iterate over the unique user identifiers...
for i = 1:B_len
% Pick all the entries of A belonging to the current user identifier...
D = A(ismember(A(:,1),B(i)),:);
% Pick two random non-repeating entries and add them to the results...
idx = datasample(1:size(D,1),2,'Replace',false);
R([R_off (R_off+1)],:) = D(idx,:);
% Properly increase the offset to the results array...
R_off = R_off + 2;
end
以下是上述代码片段的可能结果之一:
>> disp(R)
'U2' 'T13' 'A52'
'U2' 'T18' 'A52'
'U4' 'T13' 'A64'
'U4' 'T18' 'A64'
'U7' 'T14' 'A44'
'U7' 'T13' 'A341'
'U8' 'T17' 'A39'
'U8' 'T15' 'A58'
有关我使用的函数的更多信息,请参阅 Matlab 官方文档的以下页面:
关于matlab - 从 MATLAB 元胞数组中随机选择样本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49703123/