Vectorizing a for loop
Afficher commentaires plus anciens
I need some help vectorizing some code as I know that it's slowing down my run time quite a bit. I have a matrix that is sorted by rows based on one of the columns. I then use the 'unique' function to pull out the unique values of one of the columns (which also returns index vectors). The goal is then to produce average values of another column of the original matrix based on the unique values. Here is the code:
[C,idxa,idxc] = unique(A(:,17)); %pulls out unique values of col 17
C = horzcat(C,zeros(length(C),1)); %extends C by a column
for i=1:length(idxa)
C(i,2) = mean(A(eq(idxc,i),16));
end;
So you can see that I'm trying to find the mean of all of the rows in col 16 that correspond to the same unique values of col 17. This code gets the job done but it's really, really slow and I know that vectorizing it would help. Here is the code that would generate the first and last means:
C(1,2) = mean(A(idxa(1):idxa(2)-1));
C(end,2) = mean(A(idxa(end):end));
Any help is greatly appreciated!
Réponse acceptée
Plus de réponses (0)
Catégories
En savoir plus sur Resizing and Reshaping Matrices dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!