sum elements of matrix if...
5 vues (au cours des 30 derniers jours)
lets say i have two matrices:
I know what to get a matrix C has 3 rows, and each row corresponds to the indexes in B. Each column in C should have the mean of the elements in A where the index in B == row number of C.
Now I do it like this, but i want to eliminate the step with D:
for ii = 1:3;
C(ii,:) = nanmean(D);
... the faster the better :-) thanks in advance!
The problem seems to be that A(B==ii) gives a column vector, while i want it to have the same size as A.
Matt Tearle le 16 Oct 2012
Modifié(e) : Matt Tearle le 16 Oct 2012
As far as I can figure out what you're doing, this is equivalent:
CRows = max(B(:));
for i = 1:CRows;
C(i,:) = mean(A(all(B==i,2),:));
But it seems redundant to have a whole matrix of indices. Can you just do
C(i,:) = mean(A(B(:,1)==i,:));
or do you have to worry about the rows of B in some way?
EDIT TO ADD: BTW, if you have Statistics Toolbox, this will also work:
C = grpstats(A,B(:,1))
C = grpstats(A,nominal(B(:,1),,1:CRows))
The latter keeps the row of NaNs (for indices that don't appear in B).