histcounts2 — Count paired observations in 2-D histogram bins in MATLAB and RunMat.
histcounts2(X, Y) bins paired observations into a rectangular two-dimensional histogram. Edge handling, bin controls, and output layout follow MATLAB semantics.
Syntax
N = histcounts2(X, Y)
N = histcounts2(X, Y, bins)
N = histcounts2(X, Y, binsX, binsY)
N = histcounts2(X, Y, Name, Value, ...)
[N, Xedges] = histcounts2(X, Y)
[N, Xedges] = histcounts2(X, Y, bins)All supported histcounts2 forms
N = histcounts2(X, Y)
N = histcounts2(X, Y, bins)
N = histcounts2(X, Y, binsX, binsY)
N = histcounts2(X, Y, Name, Value, ...)
[N, Xedges] = histcounts2(X, Y)
[N, Xedges] = histcounts2(X, Y, bins)
[N, Xedges, Yedges] = histcounts2(X, Y)
[N, Xedges, Yedges] = histcounts2(X, Y, binsX, binsY)
[N, Xedges, Yedges] = histcounts2(X, Y, Name, Value, ...)
[N, Xedges, Yedges, binX, binY] = histcounts2(X, Y)
[N, Xedges, Yedges, binX, binY] = histcounts2(X, Y, Name, Value, ...)Inputs
X- Type
Any- Required
- Yes
- Description
- X-axis input data.
Y- Type
Any- Required
- Yes
- Description
- Y-axis input data.
bins- Type
Any- Required
- Yes
- Description
- NumBins scalar/vector or positional edge specification.
binsX- Type
Any- Required
- Yes
- Description
- X-axis NumBins scalar or edge vector.
binsY- Type
Any- Required
- Yes
- Description
- Y-axis NumBins scalar or edge vector.
name_value- Type
Any- Required
- Variadic
- Description
- Name/value pairs controlling binning and normalization.
Returns
N- Type
NumericArray- Description
- 2-D histogram bin counts.
Xedges- Type
NumericArray- Description
- X-axis bin edges.
Yedges- Type
NumericArray- Description
- Y-axis bin edges.
binX- Type
NumericArray- Description
- One-based X-bin indices, or zero for unbinned observations.
binY- Type
NumericArray- Description
- One-based Y-bin indices, or zero for unbinned observations.
Returned values from histcounts2 depend on how many outputs the caller requests.
Errors
RunMat:histcounts2:InvalidArgument- When
- Arguments are malformed, inconsistent, or unsupported.
- Message
histcounts2: invalid argument
RunMat:histcounts2:NumBinsInvalid- When
- NumBins is zero, negative, non-finite, or non-integer.
- Message
histcounts2: NumBins must be a positive finite scalar
RunMat:histcounts2:BinMethodConflict- When
- BinMethod is combined with incompatible bin controls.
- Message
histcounts2: BinMethod cannot be combined with BinEdges, NumBins, or BinWidth
Behavior
histcounts2(X, Y) requires X and Y to have the same shape, then pairs their column-major elements, and fills a numel(Xedges) - 1 by numel(Yedges) - 1 matrix of bin counts.
Bins are half-open on the right except for the last column and row, which include their upper edges so the maximum finite values are counted.
Optional arguments let you specify bin counts, explicit edges, bin limits, bin widths, and automatic binning heuristics independently for the X and Y axes.
Name/value pairs such as 'NumBins', 'XBinEdges', 'YBinEdges', 'XBinWidth', 'YBinWidth', 'BinMethod', and 'Normalization' follow MATLAB precedence and validation rules.
Pairs containing NaN in either coordinate are ignored. Infinite values participate when the chosen edges include them.
Syntax and outputs
[N, Xedges, Yedges] = histcounts2(X, Y)
[N, Xedges, Yedges] = histcounts2(X, Y, nbins)
[N, Xedges, Yedges] = histcounts2(X, Y, Xedges, Yedges)
[N, Xedges, Yedges] = histcounts2(___, Name, Value)
[N, Xedges, Yedges, binX, binY] = histcounts2(___)
X and Y are numeric vectors (or arrays flattened column-major) of equal length holding paired observations.
nbins is either a scalar bin count applied to both axes or a two-element vector [nX nY] giving separate counts for the X and Y axes.
Xedges and Yedges are monotonically increasing edge vectors. Bin k covers [edge(k), edge(k+1)); the final bin also includes its right edge so maximum values are counted.
Name/value options include 'Normalization' ('count', 'probability', 'pdf', 'countdensity', 'cumcount', 'cdf'), 'BinMethod', 'BinWidth', 'NumBins', 'XBinLimits', and 'YBinLimits'.
With five outputs, binX and binY are integer indices the same shape as the corresponding inputs, giving the X- and Y-bin that each pair falls into (0 when an observation is excluded).
Classes and execution
Counts, edges, and bin-index outputs are host double arrays. For explicit integer edges, fixed-width integer observations are compared exactly, including values beyond flintmax; generated and returned edges are double. Integer-aligned unit bins require distinct double boundaries on each axis; RunMat reports an edge-precision error when they cannot be represented.
Resident inputs are gathered through their providers before the CPU histogram runs. This materializing operation has no implemented provider reduction or fusion kernel.
Examples
Counting paired values with explicit edges
X = [0.5 1.5 2.5 3.5];
Y = [0.2 0.9 1.4 2.8];
[N, Xedges, Yedges] = histcounts2(X, Y, [0 1 2 3 4], [0 1 2 3])Expected output:
N = [1 0 0; 1 0 0; 0 1 0; 0 0 1];
Xedges = [0 1 2 3 4];
Yedges = [0 1 2 3]Specifying separate bin counts for each axis
X = [1 2 3 4];
Y = [1 2 3 4];
N = histcounts2(X, Y, 2, 4);
size(N)
sum(N, "all")Expected output:
size(N) = [2 4];
sum(N, "all") = 4Using different bin widths for X and Y
X = [1 1.5 2.4 3.7];
Y = [2 2.2 2.9 3.1];
[N, Xedges, Yedges] = histcounts2(X, Y, 'XBinWidth', 1, 'YBinWidth', 0.5);
diff(Xedges)
diff(Yedges(1:3))
sum(N, "all")Expected output:
diff(Xedges) = [1 1 1];
diff(Yedges(1:3)) = [0.5 0.5];
sum(N, "all") = 4Normalizing a 2-D histogram to probabilities
X = [0.2 0.4 1.1 1.5];
Y = [0.1 0.8 1.2 1.9];
N = histcounts2(X, Y, [0 1 2], [0 1 2], 'Normalization', 'probability')Expected output:
N = [0.5 0.0; 0.0 0.5]Ignoring NaN values in paired data
X = [1 2 NaN 3];
Y = [2 2 2 NaN];
N = histcounts2(X, Y, [0 1 2 3], [0 1 2 3]);
sum(N, "all")Expected output:
sum(N, "all") = 2Histogramming gpuArray inputs without manual gather
Gx = gpuArray([0.5 1.5 2.5]);
Gy = gpuArray([1.0 1.1 2.9]);
[counts, Xedges, Yedges] = histcounts2(Gx, Gy, [0 1 2 3], [0 2 3]);
isa(counts, 'double') % counts are returned on the CPU
countsExpected output:
isa(counts, 'double') % counts are returned on the CPU
counts = [1 0; 1 0; 0 1]Using histcounts2 with coding agents
Open a RunMat example with live inputs, then ask the agent to explain how histcounts2 changes the result.
Run a small histcounts2 example, explain the result, then change one input and compare the output.
FAQ
Do X and Y need the same size?⌄
Yes. histcounts2 requires both inputs to have the same shape. RunMat raises an error when the shapes differ, even if the element counts match.
How are the bin edges interpreted?⌄
All interior bins are [left, right), while the last row and column are [left, right], so the largest finite values are counted.
What happens to NaN, Inf, or -Inf values?⌄
Pairs containing NaN in either coordinate are ignored. Infinite values participate when the specified edges include them; otherwise, they are excluded just like MATLAB.
Can I mix explicit edges on one axis with automatic binning on the other?⌄
Yes. You can supply 'XBinEdges' while leaving the Y axis to be determined by 'NumBins', 'YBinWidth', or the default heuristics.
Which normalisation modes are supported?⌄
'count', 'probability', 'countdensity', 'pdf', 'cumcount', and 'cdf' are implemented. 'cdf' and 'cumcount' operate in column-major order so the result matches MATLAB's cumulative behaviour.
How do I request integer-aligned bins?⌄
Use 'BinMethod', 'integers' or 'XBinMethod'/'YBinMethod' with the value 'integers'. RunMat ensures the resulting edges align with integer boundaries, respecting any supplied bin limits.
What does histcounts2 do in MATLAB?⌄
histcounts2 bins paired observations into a two-dimensional histogram. It accepts two vectors X and Y of equal length and returns a matrix of bin counts plus the bin edges for each axis.
How is histcounts2 different from histcounts?⌄
histcounts bins data along a single dimension, while histcounts2 bins paired data along two dimensions simultaneously, producing a 2-D count matrix.
Can I use histcounts2 on GPU arrays in RunMat?⌄
Yes. RunMat supports histcounts2 on GPU arrays with f32 and f64 precision. The current implementation gathers to host; no GPU histogram kernel is registered.
What's the relationship between N, Xedges, and Yedges?⌄
The count matrix N has size (length(Xedges)-1) × (length(Yedges)-1): one row per X bin and one column per Y bin. Each bin covers the half-open interval [edge(k), edge(k+1)), except the final row and column, which include their upper edge so the largest finite values are counted.
How do I get a 2-D probability density from histcounts2?⌄
Pass 'Normalization', 'pdf', for example [N, Xedges, Yedges] = histcounts2(X, Y, 'Normalization', 'pdf'). Each bin value is divided by the bin area and by the total number of pairs, so sum(N .* diff(Xedges)' .* diff(Yedges), 'all') equals 1 when no samples fall outside the bin limits.
How do I use explicit bin edges with histcounts2?⌄
Supply two monotonically increasing edge vectors as the third and fourth arguments, for example Xedges = 0:0.1:1; Yedges = 0:0.1:1; N = histcounts2(X, Y, Xedges, Yedges). This gives you full control over bin placement and is the easiest way to reproduce a 2-D histogram across multiple datasets.
Related Stats functions
Hist
Summary
anova1 · binocdf · binscatter · boxplot · cdf · cdfplot · chi2cdf · corr · corrcoef · corrcov · cov · cov2corr · dummyvar · ecdf · filloutliers · fitdist · geomean · grpstats · harmmean · icdf · isoutlier · ksdensity · kstest · kurtosis · lsline · mad · mode · nanmax · normalize · normcdf · norminv · normpdf · onehotdecode · onehotencode · pca · pdf · prctile · qqplot · quantile · refline · rmse · scatterhist · skewness · tabulate · tcdf · tiedrank · tinv · tpdf · ttest · ttest2 · wblinv
Ml
bayesopt · classify · confusionmat · crossvalind · cvpartition · fitclinear · fitctree · fitlm · kmeans · knnsearch · lasso · lassoglm · linkage · lscov · mnrfit · nlparci · optimizableVariable · pdist · pdist2 · perfcurve · predict · regress · ridge · squareform · test · training · tsne
Source you can read
Every RunMat function's source is public. Read exactly how histcounts2 is executed, line by line, in Rust.
- View the source for histcounts2 in Rust on GitHub
- Learn how the RunMat runtime works
- Found a bug? Open an issue with a minimal reproduction.
About RunMat
RunMat is a runtime that executes MATLAB-syntax code fast on any GPU. The runtime is free for individuals, including freelancers; students and faculty at an academic institution, for teaching or research there; contributors to an open-source project, for work on that project; organizations with 250 or fewer people and US$10M or less in annual revenue; and anyone, for non-production use. See runmat.com/license.
- RunMat automatically optimizes your math for GPU execution on Apple, Nvidia, and AMD hardware. No code changes needed. Simulations that took hours now take minutes.
- Start running code in seconds. RunMat runs in the browser, on the desktop, or from the CLI. No license server, no IT ticket.