I created an index (groupID) for a vector A. The vector is sorted from the smallest value to the biggest one. The function and the groupID look like:
[~,groupID]=histc(A,0:5:100);
groupID = [1 1 3 3 3 5 5];
In the next step I want to calculate the average for every groupID. I did this as follows:
groupMeans = accumarray(groupID,A,[],@mean);
My problem is that accumarray fills in the output array for every skipped groupID (because e.g. 2 and 4 are missing in the index) a zero. I dont want these zeros in my output array. Is there a solution for this? My Matlab version is R2012b

 Akzeptierte Antwort

Stephen23
Stephen23 am 7 Jun. 2018
Bearbeitet: Stephen23 am 7 Jun. 2018

0 Stimmen

Use unique's third output to get the indices:
[uni,~,idx] = unique(groupID(:));
groupMeans = accumarray(idx,A,[],@mean);
[uni,groupMeans]

5 Kommentare

leonidas86
leonidas86 am 7 Jun. 2018
With unique I get hundreds of groupIDs.. This isnt nice for plotting with the bar function. Can I change the number of groupIDs?
Walter Roberson
Walter Roberson am 7 Jun. 2018
Increase the width of your bins to reduce the number of group IDs.
leonidas86
leonidas86 am 7 Jun. 2018
How can I do this?
Stephen23
Stephen23 am 7 Jun. 2018
Bearbeitet: Stephen23 am 7 Jun. 2018
"How can I do this?"
The histc help explains how the second input defines the bin ranges. If you want to change the bin ranges to make wider bins then you need to change the vector that you used (to have a larger step size).
In the original posting you used
histc(A,0:5:100);
This would create 21 bins, [0 5 10 15 20 ... 100]. To increase the width of your bins in this case you would use an increment larger than 5, such as 0:8:100 .
Note: more robust would be to use linspace(0, 100, N) where N is the number of bins you wanted.
hist() and histcounts() permit you to pass the number of bins directly.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Hilfe-Center und File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by