Accumarray for two functions?
显示 更早的评论
I'm trying to compute both the mean and SD of a set of values by group, and I can either do it with for-loop:
M = zeros(1,ngroup);
SD = zeros(1,ngroup);
for i = 1:ngroup
M(i) = mean(data(ind==i));
SD(i) = std(data(ind==i));
end
Or, alternatively use `accumarray` twice.
M = accumarray(ind,data,[],@mean);
SD = accumarray(ind,data,[],@std);
But is there a way to just use accumarray once and compute both quantities? Since accumarray is faster than for-loop, but calling it twice will be slow. Is it possible to do something like:
[M, SD] = accumarray(ind,data,[],{@mean,@std})
采纳的回答
更多回答(1 个)
The accumarray approach is certainly possible —
v = randn(250,1)
Out = accumarray(ones(size(v)), v, [], @(x){{mean(x) std(x)}})
meanv = Out{:}{1}
stdv = Out{:}{2}
Make appropriate changes to work with your data.
.
类别
在 帮助中心 和 File Exchange 中查找有关 Performance and Memory 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!