fcontour — Plot contour lines of a scalar function.
fcontour evaluates a function handle over a rectangular two-variable domain and renders contour lines from the sampled values.
Syntax
h = fcontour(f)
h = fcontour(f, xyinterval)
h = fcontour(___, Name, Value, ...)
h = fcontour(ax, ___)Inputs
f- Type
Any- Required
- Yes
- Description
- Function of two variables, z = f(x,y).
xyinterval- Type
NumericArray- Required
- No
- Default
[-5 5 -5 5]- Description
- Two- or four-element domain vector.
args- Type
Any- Required
- Yes
- Description
- Function-handle and optional domain arguments.
name_value- Type
Any- Required
- Variadic
- Description
- MeshDensity and contour name/value arguments.
ax- Type
AxesHandle- Required
- Yes
- Description
- Target axes handle.
Returns
h- Type
NumericScalar- Description
- Handle to the rendered function contour.
Errors
RunMat:fcontour:InvalidArgument- When
- Function handle, domain, mesh density, axes target, levels, or contour properties are invalid.
- Message
fcontour: invalid argument
RunMat:fcontour:EvaluationFailed- When
- A sampled function handle fails or does not return a scalar numeric value.
- Message
fcontour: function evaluation failed
RunMat:fcontour:Internal- When
- Contour construction or rendering fails unexpectedly.
- Message
fcontour: internal operation failed
RunMat:plotting:TooManyOutputs- When
- More than one output is requested from a coordinate chart constructor.
- Message
plotting: too many output arguments
Behavior
fcontour(f) samples f(x,y) on the default [-5 5 -5 5] domain.
fcontour(f, [xmin xmax ymin ymax]) uses an explicit rectangular domain; a two-element vector applies the same limits to both axes.
fcontour(ax, ___) renders into the requested axes and returns a function-contour graphics handle.
Function-handle outputs must be scalar real numeric values at every sampled point; non-finite samples are preserved as contour discontinuities.
Typed integer domain vectors, property scalars, and documented level vectors are accepted for all eight integer classes.
Options
'MeshDensity' controls the number of samples along each domain dimension. RunMat accepts exact integer counts from 3 through the resource ceiling of 400.
'LevelList' accepts a nonempty real numeric row or column vector. An integer scalar selects one explicit level, and descending level order is accepted.
'LevelStep' accepts a nonnegative finite real numeric scalar. Zero selects automatic levels and a positive integer crosses one checked contour-geometry conversion boundary.
'LineWidth' accepts a positive finite real numeric scalar and crosses one checked renderer-property conversion boundary.
'Fill' accepts logical values or the exact numeric scalar values zero and one. One adds filled contour bands beneath the contour lines.
'LineColor' accepts the documented text forms. Typed-integer RGB is a separately gated RunMat extension; the undocumented 'Color' alias is not accepted by fcontour.
'DisplayName' sets the function-contour graphics handle display name.
Integer semantics
xyinterval must be a two- or four-element row or column vector. Bounds are validated before the deliberate binary64 graphics-domain conversion.
All eight built-in integer classes are accepted for xyinterval, MeshDensity, LevelList, LevelStep, LineWidth, and numeric Fill.
Typed-integer LineColor and contour-style positional integer level specifications are RunMat extensions and are rejected unless RunMat extension mode is enabled.
Resident numeric arguments are also a RunMat extension; the compatibility gate runs before provider gathering.
Compatibility notes
RunMat currently invokes the callback once per sampled point. First-class function-contour object fidelity, matrix callback evaluation, symbolic expressions, and adaptive sampling remain deferred broader compatibility work.
The RunMat-only positional level shorthand is not part of the documented fcontour compatibility surface. Use LevelList or LevelStep for portable code.
Rendering and residency
fcontour samples arbitrary function handles on the host, then uses RunMat's existing contour renderer. There is no provider callback kernel because MATLAB callbacks are not GPU kernels.
fcontour is a callback-sampling builtin. It creates a new sampled contour plot and does not preserve input residency, because the input is a MATLAB function handle rather than a numeric provider buffer.
Callback sampling runs on the host.
The resulting contour uses the existing runmat-plot contour rendering path.
Numeric provider precision frontier
fcontour declares no direct numeric provider precision list; host generation/sampling or owner-aware gather and installed graphics rendering are separate boundaries.
Coordinate broadcasting
none
Runtime contract and boundaries
Graphics results are host double handles; fill/fill3 may return a row of handles for independently created polygon columns/groups. Sphere instead supports zero through three requested outputs: statement form plots, while output forms return host double coordinate grids. Handle aliases, value-selected options and exact graphics receiver roles are resolved by Runtime, not guessed from scalar facts.
The existing numerical and geometry owners validate coordinates, integer controls, shapes and properties. Single/double and all eight integer source classes retain their native storage wherever the object has authoritative source properties; client geometry and renderer buffers are deliberate floating boundaries, not a promise of exact wide-integer pixel positions. There is no sparse/complex plotting implementation or numeric broadcasting promise here. Logical, scalar, vector, matrix, rank and empty admission follows each documented owner below rather than a universal coercion.
RuntimeOwned preparation retains the original BuiltinArguments through suspension and completion. Eligible direct GPU routes require the live owning provider, admitted precision/storage/shape, compatible exports and installed plotting device. NoAttempt means pre-effect inapplicability, not permission to swallow export, allocation, cancellation or emission errors. Existing provider errors are propagated and ingress errors are terminal Never replay. Source-property queries and figure persistence may require explicit owner-aware readback; surface property snapshots and quiver3/patch construction are not zero-copy routes.
Canonical UserInterface capability and host-callback effects reflect scene creation/presentation; function-sampling entries additionally declare Unknown effects for arbitrary user callbacks and require the Process execution stack. NativeAndWasm means the Runtime entry is portable, not that an absent graphics host is emulated. Portable Runtime linkage introduces no separate native numerical library artifact. Rendering is a fusion boundary and distributed execution is unsupported; no numeric provider kernel or fusion primitive is invented.
Chart scratch, metadata, retained render state and the sphere coordinate builder do not yet have complete finite host allocation ownership. The shared canonical HostAllocationReceipt policy guard refuses Managed work before extraction/gather/callbacks or scene mutation, preserves ordinary Unbounded routes, and checks captured cancellation generation and policy before publication. This is an explicit L25 gap, not allocation completion. Long synchronous geometry/copy loops, renderer/provider-private allocation accounting, full MATLAB property parity, physical performance and actual example execution remain independently required.
Supported representations and remaining forms
Forms are a function handle, optional two/four-element domain, leading axes, and name/value controls. Default domain is [-5,5] in each dimension, default density 71. MeshDensity is an exact whole count 3..400. LevelList permits a nonempty row/column vector, including descending order and a single integer level. LevelStep zero chooses automatic levels; a positive finite step crosses one checked geometry boundary. Fill accepts logical or exact numeric zero/one. DisplayName and existing line styles remain supported.
The callback is evaluated once per sampled point using the actual invocation context and rooted result. Cancellation/policy is checked around each callback suspension and before publication. The retained function-contour object owns its callback through the existing session callback owner, not an ambient replacement registry. Numeric results must be scalar real; nonfinite samples represent discontinuities. Callback failures are not resampled.
All eight integer classes follow the retained domain/control capability declarations. Resident arguments, positional level shorthand and integer RGB colors are separately gated RunMat extensions before provider access. The undocumented Color/Levels aliases are rejected. Adaptive sampling, symbolic expressions, vectorized matrix callbacks and full MATLAB function-object fidelity remain unsupported rather than emulated by a fake fixture.
Examples
Plot function contours over the default domain
fcontour(@(x,y) sin(x) + cos(y));Set the domain, levels, and mesh density
h = fcontour(@(x,y) x.^2 - y.^2, [-2 2 -1 1], 'LevelList', [-1 0 1], 'MeshDensity', 75);Using fcontour with coding agents
Open a RunMat example with live inputs, then ask the agent to explain how fcontour changes the result.
Run a small fcontour example, explain the result, then change one input and compare the output.
FAQ
Does fcontour evaluate the function handle on the GPU?⌄
No. MATLAB function handles can contain arbitrary user code, so RunMat samples them on the host and then hands the sampled grid to the contour renderer.
What happens if the function returns a vector?⌄
RunMat raises RunMat:fcontour:EvaluationFailed; each sampled point must produce one scalar numeric value.
Related Plotting functions
2D Charts
area · bar · errorbar · heatmap · hist · histogram · loglog · pie · plot · scatter · semilogx · semilogy · stairs · stem
Other
addpoints · ancestor · animatedline · autumn · axes · barh · bone · caxis · cla · clf · clim · colorcube · colororder · cool · copper · copyobj · cylinder · daspect · datacursormode · dataTipTextRow · drawnow · figure · fill · fill3 · findobj · fsurf · gobjects · gray · groot · hgload · hgsave · hidden · histogram2 · hold · hot · inferno · isgraphics · ishandle · jet · line · lines · linkaxes · magma · openfig · opengl · pan · parula · patch · pink · plasma · plotmatrix · plotyy · polarhistogram · polarplot · polarscatter · print · quiver3 · ribbon · saveas · savefig · sphere · spring · stackedplot · subtitle · summer · suptitle · text · textscatter · textscatter3 · triplot · turbo · viridis · waitbar · winter · wordcloud · xlabel · xlim · xline · xscale · xtickangle · xtickformat · xticklabels · xticks · ylabel · ylim · yline · yscale · ytickangle · ytickformat · yticklabels · yticks · zlim · zoom
Source you can read
Every RunMat function's source is public. Read exactly how fcontour is executed, line by line, in Rust.
- View the source for fcontour 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.