我有这个细胞阵列:
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
我现在的问题是我的问题是否有更简单或更理想的解决方案。
答案 0 :(得分:7)
结合unique
和accumarray
,您可以实现自己想要的目标。
%// 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]