【问题标题】:Matlab random sample of a dataset数据集的 Matlab 随机样本
【发布时间】:2014-09-15 18:18:23
【问题描述】:

我有一个数据集 (Data),它是一个包含 1000 个实数的向量。我想从 Data 中随机提取 100 乘以 10 个连续数字。我不知道如何为此目的使用 Datasample。 提前感谢您的帮助。

【问题讨论】:

    标签: arrays matlab random random-sample


    【解决方案1】:

    你只能在 1 到 991 之间选择 100 个随机数:

    I = randi(991, 100, 1)
    

    然后将它们作为起点来索引 10 个连续元素:

    cell2mat(arrayfun(@(x)(Data(x:x+9)), I, 'uni', false))
    

    【讨论】:

      【解决方案2】:

      这里有一个片段,但我没有使用 Datasample,而是使用randi 生成随机索引。

      n_times = 100;
      l_data = length(Data);
      
      index_random = randi(l_data-9,n_times,1); % '- 9' to not to surpass the vector limit when you read the 10 items
      
      for ind1 = 1:n_times
          random_number(ind1,:) = Data(index_random(ind1):index_random(ind1)+9)
      end
      

      【讨论】:

      • 您应该将random_number 预先分配为zeros(n_times,10)。获取10 元素不是+9 而不是+10
      【解决方案3】:

      这类似于Dan's answer,但避免使用单元格和arrayfun,因此可能更快。

      Ns 表示您想要的连续数字的数量(在您的示例中为 10),并让Nt 表示次数(在您的示例中为 100)。那么:

      result = Data(bsxfun(@plus, randi(numel(Data)-Ns+1, Nt, 1), 0:Ns-1)); %// Nt x Ns
      

      【讨论】:

        【解决方案4】:

        这是另一个解决方案,接近@Luis,但使用cumsum 而不是bsxfun

        A = rand(1,1000); % The vector to sample
        sz = size(A,2);
        N = 100; % no. of samples
        B = 10; % size of one sample
        first = randi(sz-B+1,N,1); % the starting point for all blocks
        rand_blocks = A(cumsum([first ones(N,B-1)],2)); % the result
        

        这会产生一个 N×B 矩阵 (rand_blocks),它的每一行都是一个样本。当然,这可能是单行的,但它不会使它更快,我想保持清楚。对于较小的NB,此方法稍快一些。如果NB 变得非常大,那么bsxfun 方法会稍微快一些。此排名不受A大小的影响。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2012-11-16
          • 1970-01-01
          • 2016-10-31
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-10-16
          相关资源
          最近更新 更多