【问题标题】:What is the most MATLAB-ish way to "histogramize" a sorted cell array?什么是“直方图”排序单元数组的最 MATLAB 方式?
【发布时间】:2014-02-28 02:36:25
【问题描述】:

假设我运行的是 7/11,下面按第一列时间排序的 100x3 元胞数组是我的销售记录。

12:32:01 customer1 12
12:32:02 customer2 13
12:32:04 customer6 4
12:32:06 customer8 6
12:32:07 customer1 9
12:32:07 customer1 6
12:32:12 customer2 1
...

如您所见,每个客户都可以多次购买。例如客户 1 实际上进行了三笔不同的付款。

我现在希望计算每个客户的平均付款。 例如。假设客户 1 只支付了 3 次付款,如上所示。那么,他的平均付款将是(12+9+6)/3=9

我当然可以编写一个 for 循环来遍历所有条目并跟踪每个客户。但是,我觉得这不是 MATLAB 应该做到的。

那么完成这项任务最符合 MATLAB 的方式是什么?

【问题讨论】:

  • 很抱歉再次打扰您,但我的回答在这里有效吗?
  • @chappjc 非常抱歉忘记将其标记为答案!我的错!非常感谢您的检查!

标签: matlab cell-array


【解决方案1】:

unique 开始,为每个客户获取一个整数“密钥”,然后使用@mean 函数句柄将其输入accumarray

data = {'12:32:01','customer1',12; '12:32:02','customer2',13;...
        '12:32:04','customer6',4; '12:32:06','customer8',6;...
        '12:32:07','customer1',9; '12:32:07','customer1',6;...
        '12:32:12','customer2',1};
[customers,~,ic] = unique(data(:,2));
avePayment = accumarray(ic,[data{:,3}],[],@mean);

然后组装输出:

>> custAvgTab = [customers num2cell(avePayment)]

custAvgTab = 

    'customer1'    [9]
    'customer2'    [7]
    'customer6'    [4]
    'customer8'    [6]

恕我直言,这非常类似于 MATLAB,实际上非常直观。

注意:我将 cell2mat(data(:,3)) 替换为 [data{:,3}],因为我认为尽可能使用内置的 MATLAB 操作会更好。

注意 2:对于大数据,sprintfc('%d',avePayment) 可能比 num2cell(avePayment) 快。

【讨论】:

    【解决方案2】:

    如果您的元胞数组按如下方式组织,您可以执行以下操作:

        dataC = { ...
            {'12:32:01', 'customer1', 12}, ...
            {'12:32:02', 'customer2', 13}, ...
            {'12:32:04', 'customer6', 4}, ...
            {'12:32:06', 'customer8', 6}, ...
            {'12:32:07', 'customer1', 9}, ...
            {'12:32:07', 'customer1', 6}, ...
            {'12:32:12', 'customer2', 1}, ...
        };
    
    
    
       % get unique costumer names
       uniqueCostumers = ...
           unique(cellfun(@(c) c{2},  dataC, 'UniformOutput', false));
    
    
       for i = 1:numel(uniqueCostumers)
           customer = uniqueCostumers{i};
    
           % payments for a given customer, including zero payments
           paymetsC = cellfun(@(c) strcmp(c{2}, customer) * c{3},  dataC, 'UniformOutput', false);
    
           %convert to vector
           paymetsV = [paymetsC{:}];
    
           % calculate mean manually
           meanValue = mean(paymetsV(paymetsV ~= 0));
    
           fprintf(1, 'Mean for %s is %.2f\n', customer, meanValue);
       end
    

    这会导致:

    Mean for customer1 is 9.00
    Mean for customer2 is 7.00
    Mean for customer6 is 4.00
    Mean for customer8 is 6.00
    

    【讨论】:

      猜你喜欢
      • 2014-04-26
      • 1970-01-01
      • 2013-11-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-23
      • 1970-01-01
      • 2019-08-17
      相关资源
      最近更新 更多