Fast aggregates over overlapping subsets of a vector
2 次查看(过去 30 天)
显示 更早的评论
I have a long vector of values say x=rand(1e5,1), and a long but shorter cellarray with indices to the elements of x. I just want to compute means or sums over the vector subsets using these indices. There is a variable number of indices in cells and the indices are exclusive within each cell but may not be exclusive among the cells i.e. different cells may contain the same indices. I am aware of the accumarray but I assumed it can work for mutually exclusive sets of indices i.e. each element is used only once in aggregation. Is there any faster way to do that than in a loop:
n=1e5;
%Vector
x=rand(n,1);
%Random length indices
id=arrayfun(@(i) randperm(n, randi(n)), 1:round(n/10), 'UniformOutput',false)';
%And a loop test scenario
tic; y=zeros(size(id)); for i=1:numel(id) y(i)=mean(q(id{i})); end; t=toc
%t=2.788
Cheers
2 个评论
Dyuman Joshi
2023-2-14
Is there a need to store those indices? If not then, you can call them in each iteration and store mean accordingly -
n=1e5;
%Vector
y=zeros(1,round(n/10));
for k=1:round(n/10)
y(i)=mean(q(randperm(n,randi(n))));
end
However, You have not used x in the code and we don't know what q is, thus it's not clear what you exactly want to do.
回答(1 个)
Swaraj
2023-3-7
You are correct in saying that “accumarray” only functions for sets of indices that are mutually exclusive. You can apply a function (like mean or sum) to each cell in your cell array that contains indices by using the “cellfun” function.
Please go through the below documentation for more details.
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!