【问题标题】:Given a table of data and number of occurrences, can I create the underlying dataset? [duplicate]给定数据表和出现次数,我可以创建基础数据集吗? [复制]
【发布时间】:2013-09-10 17:25:02
【问题描述】:

我有一个描述一段数据的 2 列矩阵,以及该数据在一组中出现的次数:

A = [1    6                              
     2    2
     3    8                                                                       
     4    1 
     5    3];

鉴于此,是否有一种“优雅”的方式来生成基础数据集?即,

B = [1 1 1 1 1 1 2 2 3 3 3 3 3 3 3 3 4 5 5 5];                                       

BA 有很多方法(tabulate,使用unique and histc 等),但我找不到从AB 的任何方法。我能做的最好的就是不优雅:

B = [];
for ii = 1:size(A,1)
    B = [B repmat(A(ii,1), 1, A(ii,2))];
end

我暗中怀疑“正确”的做法是使用bsxfunaccumarray,但我没有足够的经验来理解它们的实际工作原理。

【问题讨论】:

标签: matlab run-length-encoding


【解决方案1】:

您可以将“arrayfun”与“cell2mat”结合使用:

 B = cell2mat(arrayfun(@(x,y) ones(y,1)*x, A(:,1), A(:,2), 'uniformoutput', false))'

这会导致

B =

  Columns 1 through 16

     1     1     1     1     1     1     2     2     3     3     3     3     3     3     3     3

  Columns 17 through 20

     4     5     5     5

【讨论】:

    【解决方案2】:

    这里还有一个选项。我不会称之为优雅,但它非常有效。

    ndx = cumsum([1; A(:,2)]);
    B = zeros(1, ndx(end)-1);
    B(ndx(1:end-1)) = 1;
    B = A(cumsum(B), 1).';
    

    【讨论】:

      【解决方案3】:

      也不是很优雅,但这可能有效:

      B = {A(:,1)*ones(1,A(:,2)};
      B = [B{:}];
      

      没有matlab来检查语法,想法是从

      中删除循环
      B=[];
      for ii=1:size(A,1)
         B=[B A(i,1)*ones(1,A(i,2)];
      end;
      

      【讨论】:

        【解决方案4】:

        这是使用bsxfun的解决方案:

        B = A(1+sum(bsxfun(@lt, cumsum(A(:,2)), 1:sum(A(:,2)))), 1).';
        

        【讨论】:

          【解决方案5】:

          这类似于 H.Muster 的帖子

          使用repmat

          B=cell2mat(arrayfun(@(x,y)(repmat(x,y,1) ), A(:,1), A(:,2), ...
                                             'UniformOutput', false));
          

          B' 是预期的输出。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2014-06-01
            • 1970-01-01
            • 1970-01-01
            • 2019-05-13
            • 2021-12-16
            • 1970-01-01
            • 1970-01-01
            • 2021-08-21
            相关资源
            最近更新 更多