matlab - 从 MATLAB 元胞数组中随机选择样本

标签 matlab random sample cell-array

我在 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/

相关文章:

image-processing - 在 MATLAB 中处理图像的一部分

循环错误中的 Matlab 图

image - 在matlab中重命名图像文件名

c# - C# 线程中的 Bouncy CaSTLe SecureRandom 安全吗?

ios - 无法在标签中显示经文

java - 如何随机生成一个函数,该函数是 <10000 的整数的排列

python - 在 pandas 中对整个 DataFrame 进行采样时,避免连续列中出现两个相同的值

python - 从一组中采样一个元素,时间复杂度为 O(1)

用于请求和下载 Bing 广告报告的 PHP 示例无法正常工作

Matlab:如何在使用给定函数的路径上查找函数