ksdensity — Normal-kernel estimates for univariate observations.
Estimate a probability density, cumulative distribution or survivor function and optionally draw the resulting curve.
Syntax
[f,xi,bw] = ksdensity(x,Name,Value,...)
[f,xi,bw] = ksdensity(x,pts,Name,Value,...)
ksdensity(ax,x,Name,Value,...)Inputs
x- Type
NumericArray- Required
- Yes
- Default
- —
- Description
- Real single/double univariate observations; NaNs are omitted.
name_value_pairs- Type
Any- Required
- Variadic
- Default
- —
- Description
- Bandwidth, NumPoints, Function, Kernel and Support controls.
pts- Type
NumericArray- Required
- No
- Default
[]- Description
- Evaluation vector, or numeric [] for the automatic grid.
ax- Type
Any- Required
- Yes
- Default
- —
- Description
- Typed axes target for the zero-output plotting form; numeric handle IDs are not used to reinterpret scalar samples.
Returns
f- Type
NumericArray- Description
- Double PDF, CDF or survivor estimates, with the evaluation-point shape.
xi- Type
NumericArray- Description
- Explicit points with their original floating class/shape, or a generated double row vector.
bw- Type
NumericArray- Description
- Positive reusable double bandwidth.
Errors
RunMat:ksdensity:InvalidArgument- When
- Sample/point class or geometry, bandwidth identification, numeric controls, supported option surface, device intent or output count is invalid.
- Message
ksdensity: invalid argument
Samples, points and outputs
[f,xi,bw]=ksdensity(x) accepts real single/double univariate vectors. NaN samples are omitted; at least one observation is required and infinite samples are invalid. Bivariate data, integer/logical/complex samples, sparse arrays and distributed execution are unsupported, not silently converted.
ksdensity(x,pts,...) evaluates at an explicit floating vector. xi retains pts' original class, values and shape, including a single-precision scalar point. Numeric [] requests the automatic grid. Estimates f and the reusable positive bandwidth bw are double, even for single samples; no MATLAB single-output-class parity is claimed. NaN evaluation points propagate NaN; infinite evaluation points use the normal-kernel limiting values.
The RunMat automatic grid has100 double row-vector points from min(x)-3*bw through max(x)+3*bw. NumPoints changes that count; one point uses the upper endpoint, following linspace endpoint semantics. Collapsed coordinates at floating precision are not expanded with an arbitrary extra scale. If padded endpoints are not representable, supply explicit points. This grid policy is stated explicitly rather than claimed to reproduce undocumented MATLAB grid details.
Bandwidth and supported options
Bandwidth accepts a finite positive single/double scalar or normal-approx. The normal-reference rule uses h=(MAD/Phi^-1(0.75))*(4/(3*n))^(1/5), with the median absolute deviation about the sample median. If ties give zero MAD but samples are nonconstant, their actual sample standard deviation supplies the scale. If no positive finite automatic scale is identifiable, including constant or singleton samples, provide Bandwidth explicitly; no arbitrary unit width is substituted. Explicit positive Bandwidth supports those samples normally.
Case-insensitive options are Bandwidth, NumPoints, Function, Kernel and Support. Function is pdf (default), cdf or survivor. Kernel must be normal and Support must be unbounded; these select the implemented kernel/domain, not aliases for other kernels or boundary corrections. NumPoints is a positive single/double scalar integer and cannot be combined with nonempty explicit points. Later duplicate controls replace earlier ones.
Plug-in bandwidths, custom/non-normal kernels, censoring, weights, bounded/positive support, BoundaryCorrection, inverse CDF and cumulative hazard are unsupported and rejected. None is accepted and ignored. PDF estimates are not clipped to one; densities above one and representationally infinite peaks can be valid. Log-domain normal-density reduction preserves recoverable small estimates rather than dividing an already-underflowed kernel value by bandwidth.
Plotting and execution
With no outputs, ksdensity draws its curve through RunMat's ordinary plot owner and requires plot-core. A typed leading axes target is supported only in that zero-output form. Numeric handle IDs never reinterpret a numeric scalar sample based on ambient UI state. Requested numerical outputs do not create plots or require UI capability.
Only authenticated automatic residency can use the original context's host gather boundary for samples, points and controls. Explicit or unproven device intent is rejected before any argument transfer; use gather explicitly for host estimates. There is no provider-native KDE kernel, numerical fusion producer or separate explicit-host-fallback extension.
Finite host-memory execution is unsupported and refuses before gather, sorting or estimate allocation because the workspaces have no complete allocation certificate. Sample scans, the shared resumable sort and kernel reduction cooperate with the original execution context. Plotting uses the existing exact lazy continuation owner; no new thread or stack-size policy is introduced. Original provider and typed cancellation failures are not replayed or relabeled.
Examples
Evaluate a two-point Gaussian mixture
[f,xi,bw] = ksdensity([-1;1],[0;1],'Bandwidth',1);Inspect the normal-reference estimate
[f,xi,bw] = ksdensity([-2;-1;0;1;2]);Using ksdensity with coding agents
Open a RunMat example with live inputs, then ask the agent to explain how ksdensity changes the result.
Run a small ksdensity example, explain the result, then change one input and compare the output.
Related Stats functions
Summary
anova1 · binocdf · binscatter · boxplot · cdf · cdfplot · chi2cdf · corr · corrcoef · corrcov · cov · cov2corr · dummyvar · ecdf · filloutliers · fitdist · geomean · grpstats · harmmean · icdf · isoutlier · 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
Random
binornd · bootstrp · datasample · dividerand · exprnd · gamrnd · gpurng · lhsdesign · mvnrnd · normrnd · random · randsample · rng · trnd · unidrnd · unifrnd · wblrnd
Hist
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.