histcounts
Histogram bin counts
Syntax
Description
[
partitions theN
,edges
] = histcounts(X
)X
values into bins, and returns the count in each bin, as well as the bin edges. Thehistcounts
function uses an automatic binning algorithm that returns bins with a uniform width, chosen to cover the range of elements inX
and reveal the underlying shape of the distribution.
counts only the elements inN
= histcounts(C
,Categories
)C
whose value is equal to the subset of categories specified byCategories
.
[
also returns the categories that correspond to each count inN
,Categories
] = histcounts(___)N
using either of the previous syntaxes for categorical arrays.
[___] = histcounts(___,
uses additional options specified by one or moreName,Value
)Name,Value
pair arguments using any of the input or output argument combinations in previous syntaxes. For example, you can specify'BinWidth'
and a scalar to adjust the width of the bins for numeric data. For categorical data, you can specify'Normalization'
and either'count'
,'countdensity'
,'probability'
,'pdf'
,'cumcount'
, or'cdf'
.
Examples
Bin Counts and Bin Edges
Distribute 100 random values into bins.histcounts
自动选择一个合适的宽度reveal the underlying distribution of the data.
X = randn(100,1); [N,edges] = histcounts(X)
N =1×72 17 28 32 16 3 2
edges =1×8-3 -2 -1 0 1 2 3 4
Specify Number of Bins
Distribute 10 numbers into 6 equally spaced bins.
X = [2 3 5 7 11 13 17 19 23 29]; [N,edges] = histcounts(X,6)
N =1×62 2 2 2 1 1
edges =1×70 4.9000 9.8000 14.7000 19.6000 24.5000 29.4000
Specify Bin Edges
Distribute 1,000 random numbers into bins. Define the bin edges with a vector, where the first element is the left edge of the first bin, and the last element is the right edge of the last bin.
X = randn(1000,1); edges = [-5 -4 -2 -1 -0.5 0 0.5 1 2 4 5]; N = histcounts(X,edges)
N =1×100 24 149 142 195 200 154 111 25 0
Normalized Bin Counts
Distribute all of the prime numbers less than 100 into bins. Specify'Normalization'
as'probability'
to normalize the bin counts so thatsum(N)
is1
. That is, each bin count represents the probability that an observation falls within that bin.
X = primes(100); [N,edges] = histcounts(X,'Normalization','probability')
N =1×40.4000 0.2800 0.2800 0.0400
edges =1×50 30 60 90 120
Determine Bin Placement
Distribute 100 random integers between -5 and 5 into bins, and specify'BinMethod'
as'integers'
to use unit-width bins centered on integers. Specify a third output forhistcounts
to return a vector representing the bin indices of the data.
X = randi([-5,5],100,1); [N,edges,bin] = histcounts(X,'BinMethod','integers');
Find the bin count for the third bin by counting the occurrences of the number3
in the bin index vector,箱子
. The result is the same asN(3)
.
count = nnz(bin==3)
count = 8
Categorical Bin Counts
Create a categorical vector that represents votes. The categories in the vector are'yes'
,'no'
, or'undecided'
.
A = [0 0 1 1 1 0 0 0 0 NaN NaN 1 0 0 0 1 0 1 0 1 0 0 0 1 1 1 1]; C = categorical(A,[1 0 NaN],{'yes','no','undecided'})
C =1x27 categoricalColumns 1 through 9 no no yes yes yes no no no no Columns 10 through 16 undecided undecided yes no no no yes Columns 17 through 25 no yes no yes no no no yes yes Columns 26 through 27 yes yes
Determine the number of elements that fall into each category.
[N,Categories] = histcounts(C)
N =1×311 14 2
类别=1x3 cell{'yes'} {'no'} {'undecided'}
Input Arguments
X
—Data to distribute among bins
vector|matrix|multidimensional array
Data to distribute among bins, specified as a vector, matrix, or multidimensional array. IfX
is not a vector, thenhistcounts
treats it as a single column vector,X(:)
.
histcounts
ignores allNaN
values. Similarly,histcounts
ignoresInf
and-Inf
values unless the bin edges explicitly specifyInf
or-Inf
as a bin edge.
Data Types:single
|double
|int8
|int16
|int32
|int64
|uint8
|uint16
|uint32
|uint64
|logical
|datetime
|duration
C
—Categorical data
categorical array
Categorical data, specified as a categorical array.histcounts
ignores undefined categorical values.
Data Types:categorical
nbins
—Number of bins
positive integer
Number of bins, specified as a positive integer. If you do not specifynbins
, thenhistcounts
automatically calculates how many bins to use based on the values inX
.
Example:[N,edges] = histcounts(X,15)
uses 15 bins.
edges
—Bin edges
vector
Bin edges, specified as a vector.edges(1)
is the left edge of the first bin, andedges(end)
is the right edge of the last bin.
For datetime and duration data,edges
must be a datetime or duration vector in monotonically increasing order.
Data Types:single
|double
|int8
|int16
|int32
|int64
|uint8
|uint16
|uint32
|uint64
|logical
|datetime
|duration
Categories
—Categories included in count
all categories(default) |string vector|cell vector of character vectors|pattern
scalar|categorical vector
Categories included in count, specified as a string vector, cell vector of character vectors,pattern
scalar, or categorical vector. By default,histcounts
uses a bin for each category in categorical arrayC
. UseCategories
to specify a unique subset of the categories instead.
Example:h = histcounts(C,["Large","Small"])
counts only the categorical data in the categoriesLarge
andSmall
.
Example:h = histcounts(C,"Y" + wildcardPattern)
counts categorical data in all the categories whose names begin with the letterY
.
Data Types:string
|cell
|pattern
|categorical
Name-Value Arguments
Specify optional pairs of arguments asName1=Value1,...,NameN=ValueN
, whereName
is the argument name andValue
is the corresponding value. Name-value arguments must appear after other arguments, but the order of the pairs does not matter.
R2021a之前,用逗号来分隔每一个名字d value, and encloseName
in quotes.
Example:[N,edges] = histcounts(X,'Normalization','probability')
normalizes the bin counts inN
, such thatsum(N)
is 1.
BinLimits
—Bin limits
two-element vector
Bin limits, specified as a two-element vector,[bmin,bmax]
. This option bins only the values inX
that fall betweenbmin
andbmax
inclusive; that is,X(X>=bmin & X<=bmax)
.
This option does not apply to categorical data.
Example:[N,edges] = histcounts(X,'BinLimits',[1,10])
箱子s only the values inX
that are between1
and10
inclusive.
BinMethod
—Binning algorithm
'auto'
(default) |'scott'
|'fd'
|'integers'
|'sturges'
|'sqrt'
| ...
Binning algorithm, specified as one of the values in this table.
Value |
Description |
---|---|
|
的default |
|
Scott’s rule is optimal if the data is close to being normally distributed, but is also appropriate for most other distributions. It uses a bin width of |
|
的Freedman-Diaconis rule is less sensitive to outliers in the data, and may be more suitable for data with heavy-tailed distributions. It uses a bin width of |
|
的integer rule is useful with integer data, as it creates a bin for each integer. It uses a bin width of 1 and places bin edges halfway between integers. To prevent from accidentally creating too many bins, a limit of 65536 bins (216这条规则可以创建)。如果数据range is greater than 65536, then wider bins are used instead. Note
|
|
Sturges’ rule is a simple rule that is popular due to its simplicity. It chooses the number of bins to be |
|
的Square Root rule is another simple rule widely used in other software packages. It chooses the number of bins to be |
histcounts
does not always choose the number of bins using these exact formulas. Sometimes the number of bins is adjusted slightly so that the bin edges fall on "nice" numbers.
For datetime data, the bin method can be one of these units of time:
'second' |
'month' |
'minute' |
'quarter' |
'hour' |
'year' |
'day' |
'decade' |
'week' |
'century' |
For duration data, the bin method can be one of these units of time:
'second' |
'day' |
'minute' |
'year' |
'hour' |
If you specifyBinMethod
with datetime or duration data, thenhistcounts
can use a maximum of 65,536 bins (or 216). If the specified bin duration requires more bins, thenhistcounts
uses a larger bin width corresponding to the maximum number of bins.
This option does not apply to categorical data.
Example:[N,edges] = histcounts(X,'BinMethod','integers')
uses bins centered on integers.
BinWidth
—Width of bins
scalar
Width of bins, specified as a scalar. If you specifyBinWidth
, thenhistcounts
can use a maximum of 65,536 bins (or216). If the specified bin width requires more bins, thenhistcounts
uses a larger bin width corresponding to the maximum number of bins.
For datetime and duration data, the value of'BinWidth'
can be a scalar duration or calendar duration.
This option does not apply to categorical data.
Example:[N,edges] = histcounts(X,'BinWidth',5)
uses bins with a width of 5.
BinEdges
—Edges of bins
numeric vector
Edges of bins, specified as a numeric vector. The first vector element specifies the left edge of the first bin. The last element specifies the right edge of the last bin. If you do not specify the bin edges, thenhistcounts
automatically determines the location of the bin edges.
This option does not apply to categorical data.
Data Types:single
|double
|int8
|int16
|int32
|int64
|uint8
|uint16
|uint32
|uint64
|logical
Normalization
—Type of normalization
'count'
(default) |'probability'
|'countdensity'
|'pdf'
|'cumcount'
|'cdf'
Type of normalization, specified as one of the values in this table. For each bini
:
is the bin value.
is the number of elements in the bin.
is the width of the bin.
is the number of elements in the input data. This value can be greater than the binned data if the data contains
NaN
,NaT
, or
values, or if some of the data lies outside the bin limits.
Value | Bin Values | Notes |
---|---|---|
'count' (default) |
|
|
'countdensity' |
|
Note
|
'cumcount' |
|
|
'probability' |
|
|
'pdf' |
|
Note
|
'cdf' |
|
|
Example:[N,edges] = histcounts(X,'Normalization','pdf')
箱子s the data using the probability density function estimate.
NumBins
—Number of bins
positive integer
Number of bins, specified as a positive integer. If you do not specifyNumBins
, thenhistcounts
automatically calculates how many bins to use based on the input data.
This option does not apply to categorical data.
Output Arguments
N
— Bin counts
row vector
Bin counts, returned as a row vector.
edges
— Bin edges
vector
Bin edges, returned as a vector.edges(1)
is the left edge of the first bin, andedges(end)
is the right edge of the last bin.
箱子
— Bin indices
数组
Bin indices, returned as an array of the same size asX
. Each element in箱子
describes which numbered bin contains the corresponding element inX
.
A value of0
in箱子
indicates an element which does not belong to any of the bins (for example, aNaN
value).
Categories
— Categories included in count
cell vector of character vectors
Categories included in count, returned as a cell vector of character vectors.Categories
contains the categories inC
that correspond to each count inN
.
Tips
的behavior of
histcounts
is similar to that of thediscretize
function. Usehistcounts
to find the number of elements in each bin. On the other hand, usediscretize
to find which bin each element belongs to (without counting).
Extended Capabilities
Tall Arrays
Calculate with arrays that have more rows than fit in memory.
Usage notes and limitations:
Some input options are not supported. The allowed options are:
'BinWidth'
'BinLimits'
'Normalization'
'BinMethod'
— The'auto'
and'scott'
本方法是相同的。的'fd'
箱子method is not supported.
的
Categories
input argument does not support pattern expressions.
For more information, seeTall Arrays.
C/C++ Code Generation
Generate C and C++ code using MATLAB® Coder™.
Usage notes and limitations:
Code generation does not support sparse matrix inputs for this function.
If you do not supply bin edges, then code generation might require variable-size arrays and dynamic memory allocation.
的
Categories
input argument does not support pattern expressions.
GPU Code Generation
Generate CUDA® code for NVIDIA® GPUs using GPU Coder™.
Usage notes and limitations:
Code generation does not support sparse matrix inputs for this function.
If you do not supply bin edges, then code generation might require variable-size arrays and dynamic memory allocation.
的
Categories
input argument does not support pattern expressions.
Thread-Based Environment
Run code in the background using MATLAB®backgroundPool
or accelerate code with Parallel Computing Toolbox™ThreadPool
.
This function fully supports thread-based environments. For more information, seeRun MATLAB Functions in Thread-Based Environment.
GPU Arrays
Accelerate code by running on a graphics processing unit (GPU) using Parallel Computing Toolbox™.
Usage notes and limitations:
64-bit integers are not supported.
For more information, seeRun MATLAB Functions on a GPU(Parallel Computing Toolbox).
Version History
Open Example
You have a modified version of this example. Do you want to open this example with your edits?
MATLAB Command
You clicked a link that corresponds to this MATLAB command:
Run the command by entering it in the MATLAB Command Window. Web browsers do not support MATLAB commands.
Select a Web Site
Choose a web site to get translated content where available and see local events and offers. Based on your location, we recommend that you select:.
You can also select a web site from the following list:
How to Get Best Site Performance
Select the China site (in Chinese or English) for best site performance. Other MathWorks country sites are not optimized for visits from your location.
Americas
- América Latina(Español)
- Canada(English)
- United States(English)
Europe
- Belgium(English)
- Denmark(English)
- Deutschland(Deutsch)
- España(Español)
- Finland(English)
- France(Français)
- Ireland(English)
- Italia(Italiano)
- Luxembourg(English)
- Netherlands(English)
- Norway(English)
- Österreich(Deutsch)
- Portugal(English)
- Sweden(English)
- Switzerland
- United Kingdom(English)