contour3 — Create 3-D contour line plots in MATLAB and RunMat.
contour3 creates 3-D contour line plots from scalar fields. It accepts core contour-style inputs but places each isoline at its scalar Z level rather than projecting onto a flat plane.
Syntax
h = contour3(Z)
h = contour3(Z, N)
h = contour3(Z, V)
h = contour3(Z, Name, Value, ...)
h = contour3(Z, V, Name, Value, ...)
h = contour3(X, Y, Z)All supported contour3 forms
h = contour3(Z)
h = contour3(Z, N)
h = contour3(Z, V)
h = contour3(Z, Name, Value, ...)
h = contour3(Z, V, Name, Value, ...)
h = contour3(X, Y, Z)
h = contour3(X, Y, Z, N)
h = contour3(X, Y, Z, V)
h = contour3(X, Y, Z, V, Name, Value, ...)
h = contour3(X, Y, Z, N, Name, Value, ...)
h = contour3(ax, ...)Inputs
Z- Type
NumericArray- Required
- Yes
- Description
- Contour height grid.
N- Type
NumericScalar- Required
- Yes
- Description
- Requested contour level count.
V- Type
NumericArray- Required
- Yes
- Description
- Explicit contour level values.
props- Type
Any- Required
- Variadic
- Description
- Name/value contour options.
V- Type
Any- Required
- Yes
- Description
- Contour level count/value vector.
X- Type
NumericArray- Required
- Yes
- Description
- X coordinate vector matching Z columns or meshgrid matrix matching Z.
Y- Type
NumericArray- Required
- Yes
- Description
- Y coordinate vector matching Z rows or meshgrid matrix matching Z.
ax- Type
Any- Required
- Yes
- Description
- Target axes object.
args- Type
Any- Required
- Variadic
- Description
- Any supported contour data, level, line-specification, and property arguments.
Returns
h- Type
NumericScalar- Description
- Handle to contour line plot.
Errors
RunMat:contour3:InvalidArgument- When
- Contour input arrays, level arguments, or name/value options are invalid.
- Message
contour3: invalid argument
RunMat:contour3:Internal- When
- Internal contour render preparation fails unexpectedly.
- Message
contour3: 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
contour3(Z) uses implicit X and Y axes derived from the Z matrix shape.
contour3(X, Y, Z) accepts explicit vector axes or meshgrid-style X and Y matrices.
A scalar fourth argument selects the number of contour levels; a vector fourth argument selects exact contour levels.
LineSpec color tokens such as 'k' and name-value pairs such as 'LineWidth' are accepted.
GPU-aware contour generation is used when the shared plotting path can operate directly on GPU-resident scalar fields.
Options
'LevelList' / 'Levels' accepts an explicit, strictly increasing vector of contour values.
'LevelStep' specifies the spacing between generated contour levels.
'LineColor' accepts MATLAB color strings, RGB triples, 'auto', and 'none'.
'LineWidth' controls contour line thickness.
Rendering and residency
contour3 uses the shared contour-generation path and can keep GPU-resident Z inputs on device through the WGPU plotting pipeline.
contour3 preserves GPU residency when the shared WGPU plotting context can consume the Z buffer directly. If that path is unavailable, RunMat gathers once and builds the same contour geometry on the CPU.
Declared source precision and class coverage
single
double
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
Core forms are Z; Z plus level count/vector; X,Y,Z plus optional levels; leading axes; optional LineSpec followed by name/value pairs. Z must be at least 2-by-2 and nonconstant after the existing contour validation. Coordinate vectors are strictly monotonic; meshgrid-style coordinate matrices must have the correct identity and varying dimensions. Empty, mismatched or degenerate grids fail rather than becoming an invented 1-by-1 field.
Level counts are positive finite whole scalars subject to the existing one-million-level materialization ceiling. Explicit levels are strictly increasing, with [k k] representing a single level. LevelStep is positive finite; LineWidth is positive finite. Levels/LevelList, LevelStep, LineColor/Color, LineWidth and the existing LevelListMode controls use one shared parser. Integer order/count/meshgrid checks precede floating conversion; integer RGB 0/1 channels use the existing separately gated contour extension.
The returned value is the RunMat graphics handle, not MATLAB contour-matrix M or [M,c] output. Full contour labels, broad properties and post-construction coordinate mutation remain gaps. Eligible floating Z can use prepared GPU contours; axes/control reads and integer grids gather through their actual owner. A prepared composite publishes its requested parts only after their construction succeeds; errors are not fallback signals.
Contour3 uses the same parser but places each isoline at its own level through ContourZMode::Level. Its geometry fixture verifies actual vertex heights; the public contour getter currently exposes only limited metadata (including base ZData), not the full vertex arrays.
Examples
Create a basic 3-D contour plot
[X, Y] = meshgrid(-2:0.25:2, -2:0.25:2);
Z = X .* exp(-X.^2 - Y.^2);
contour3(X, Y, Z);Use explicit contour levels with high-contrast lines
[X, Y] = meshgrid(linspace(-3, 3, 80), linspace(-3, 3, 80));
Z = sin(X) .* cos(Y);
contour3(X, Y, Z, [-0.75 -0.25 0.25 0.75], 'Color', [0.05 0.35 0.95], 'LineWidth', 2.25);
zlabel('Potential');
view(45, 30);Inspect the returned contour handle
Z = peaks(40);
h = contour3(Z, 12, 'Color', [0.9 0.2 0.05], 'LineWidth', 2.0);
get(h, 'Type')Expected output:
ans =
'contour'Rendered contour3 example
[X, Y] = meshgrid(linspace(-3, 3, 100), linspace(-3, 3, 100));
Z = sin(X).*cos(Y) + 0.25*cos(2*X + Y);
levels = [-0.9 -0.6 -0.3 0 0.3 0.6 0.9];
contour3(X, Y, Z, levels, 'LineWidth', 2);
title('Potential Field Levels');
xlabel('x');
ylabel('y');
zlabel('Potential');
view(42, 28);
grid on;
Compare this result with other chart types in the plot examples.
Using contour3 with coding agents
Open a RunMat example with live inputs, then ask the agent to explain how contour3 changes the result.
Run a small contour3 example, explain the result, then change one input and compare the output.
FAQ
How is contour3 different from contour?⌄
contour draws contour lines on a single flat plane. contour3 places each contour line at its own scalar level on the Z axis, which makes level height visible in the 3-D camera.
Can contour3 be combined with surface plots?⌄
Yes. Use hold on to overlay contour3 with surf, mesh, plot3, or scatter3. Because contour3 is camera-aware, it shares the same 3-D axes state as other 3-D plot types.
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 · fcontour · 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
More plotting resources
Source you can read
Every RunMat function's source is public. Read exactly how contour3 is executed, line by line, in Rust.
- View the source for contour3 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.