Accumarray for two functions?
Show older comments
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})
Accepted Answer
More Answers (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.
.
Categories
Find more on Performance and Memory in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!