Is there a better way to compute metrics on labeled array elements.
4 次查看(过去 30 天)
显示 更早的评论
For example, I have a 1d double array 'data' and a 1d cell array of strings called 'labels'. For each unique label I want the mean of the data. The best I have come up with is below. I don't believe this is fully vectorized. Is there a better way?
%%make sample dataset
n = 1000;
data = rand(n,1);
labels = char(randsample(97:122,n,true)');%[a-z]
%%get means for each label
[uniLab,~,labIdx] = unique(labels,'stable');% stable for speed
mu = arrayfun(@(x) mean(data(labIdx==x)),1:numel(uniLab));
0 个评论
采纳的回答
Walter Roberson
2018-6-17
2 个评论
Walter Roberson
2018-6-17
The last step of your code can be replaced by
accumarray(labIdx, data, [], @mean)
更多回答(1 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Cell Arrays 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!