【问题标题】:Averaging a row of a cell array dependent on a string in another row平均依赖于另一行中的字符串的单元格数组的一行
【发布时间】:2015-07-08 10:02:44
【问题描述】:

我有这个元胞数组:

times = {'plot'      'plot'      'plot'      'plot'      'plot'      'hist'      'plot'      'plot'      'plot'      'plot'  ;
         [0.0042]    [0.0026]    [0.0032]    [0.0054]    [0.0049]    [0.0106]    [0.0038]    [0.0026]    [0.0030]    [0.0026]}

现在我想为第一行中的每种类型创建一个平均值并将其保存到一个新单元格中,如下所示:

result = {'hist'      'plot'  ;  
          [0.0106]    [0.0036];
          [     1]    [     9]}

第一行是类型,第二行是平均值,第三行是元素个数。

我用这段代码解决了我的问题:

labels = unique(times(1,:));
result = cell(3,numel(labels));

for i = 1 : numel(labels)
    result(1,i) = labels(i);
    times2avg = cell2mat(times(2,strcmp(times(1,:), labels(i))));
    result{2,i} = mean(times2avg);
    result{3,i} = numel(times2avg);
end

我现在的问题是是否有更简单或更理想的解决方案来解决我的问题。

【问题讨论】:

  • @MaximilianAst 虽然你接受一个答案是件好事,但许多人不会用一个接受的答案来看待问题。在接受之前等待几个小时通常是一件好事,这样回答者可以获得最大的票数。

标签: matlab grouping average cell-array


【解决方案1】:

结合使用uniqueaccumarray,您可以实现您想要的。

%// example data
times = { 'plot' 'plot' 'plot' 'plot' 'hist' 'plot'; 
            [1]    [2]    [3]   [4]    [5]    [6] }
%// extract data
data = [times{2,:}]

%// get types and their locations
[types, ~, subs] = unique(times(1,:))

%// calculate average values
avgs = accumarray(subs(:),data(:),[],@mean)

%// count occurences
nums = accumarray(subs(:),data(:),[],@numel)

%// gather everything for output
result = [types; num2cell(avgs.'); num2cell(nums.')]

result = 

    'hist'    'plot'  
    [   5]    [3.2000]
    [   1]    [     5]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-09
    相关资源
    最近更新 更多