Fast aggregates over overlapping subsets of a vector
2 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
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 comentarios
Dyuman Joshi
el 14 de Feb. de 2023
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.
Respuestas (1)
Swaraj
el 7 de Mzo. de 2023
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 comentarios
Ver también
Categorías
Más información sobre Logical en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!