问题
I am trying to replace a use of the old hist function by the new histcounts which performs faster at binning and counting than hist. However, I am struggling to achieve the exact same results from histcounts that I got from hist.
I am aware that histcounts returns the bin edges rather than the binCenters. However, the counts should be identical and the bin edges should be convertible to bin centers, as far as I understand.
The Matlab reference page for replacing hist with histcounts (see http://se.mathworks.com/help/matlab/creating_plots/replace-discouraged-instances-of-hist-and-histc.html) does not touch upon this inequality of results and only converts binCenters to binEdges (not the other way around)
This small piece of code helps to illustrate my problem.
A = randn(100,2);
[N1,binCenters1] = hist(A(:,1),10);
[N2,binEdges2] = histcounts(A(:,1),10);
binCenters2 = mean([binEdges2(1:end-1);binEdges2(2:end)]);
N = [N1;N2;abs(N1-N2)];
binCenters = [binCenters1;binCenters2;abs(binCenters1-binCenters2)];
It outputs
N:
1 2 4 7 28 28 16 8 4 2
1 0 5 6 23 34 15 10 4 2
0 2 1 1 5 6 1 2 0 0
binCenters:
-2,46697043006437 -1,93055060769862 -1,39413078533287 -0,857710962967123 -0,321291140601375 0,215128681764373 0,751548504130121 1,28796832649587 1,82438814886162 2,36080797122737
-2,71500000000000 -2,14500000000000 -1,57500000000000 -1,00500000000000 -0,435000000000000 0,135000000000000 0,705000000000000 1,27500000000000 1,84500000000000 2,41500000000000
0,248029569935633 0,214449392301381 0,180869214667129 0,147289037032877 0,113708859398625 0,0801286817643727 0,0465485041301204 0,0129683264958687 0,0206118511383833 0,0541920287726354
As you can see, the difference is nonzero.
来源:https://stackoverflow.com/questions/38263792/how-do-i-get-identical-results-from-the-old-hist-and-the-new-histcounts-function