Skip to content

A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.

feat: mo.ui.matrix() (#8354)

Akshay Agrawal6e6d801ec2ee
diff --git a/docs/_static/example-thumbs/matrix.png b/docs/_static/example-thumbs/matrix.png
new file mode 100644
index 0000000000..7bf4d86516
Binary files /dev/null and b/docs/_static/example-thumbs/matrix.png differ
diff --git a/docs/_static/example-thumbs/vector.png b/docs/_static/example-thumbs/vector.png
new file mode 100644
index 0000000000..ad5197c56c
Binary files /dev/null and b/docs/_static/example-thumbs/vector.png differ
diff --git a/docs/api/inputs/index.md b/docs/api/inputs/index.md
index d7fe22a96b..43c60cd1ce 100644
--- a/docs/api/inputs/index.md
+++ b/docs/api/inputs/index.md
@@ -21,6 +21,8 @@ powerful notebooks and apps. These elements are available in `marimo.ui`.
| [`marimo.ui.file`][marimo.ui.file] | File uploads |
| [`marimo.ui.file_browser`][marimo.ui.file_browser] | Browse files |
| [`marimo.ui.form`][marimo.ui.form] | Create forms |
+| [`marimo.ui.matrix`][marimo.ui.matrix] | Interactive matrix editor |
+| [`marimo.ui.vector`][marimo.ui.vector] | Interactive vector editor |
| [`marimo.ui.microphone`][marimo.ui.microphone] | Record audio |
| [`marimo.ui.multiselect`][marimo.ui.multiselect] | Multiple selection |
| [`marimo.ui.number`][marimo.ui.number] | Number inputs |
diff --git a/docs/api/inputs/matrix.md b/docs/api/inputs/matrix.md
new file mode 100644
index 0000000000..148b82b451
--- /dev/null
+++ b/docs/api/inputs/matrix.md
@@ -0,0 +1,27 @@
+# Matrix
+
+/// marimo-embed
+
+```python
+def __():
+ matrix = mo.ui.matrix(
+ [[1, 0, 0], [0, 1, 0], [0, 0, 1]],
+ min_value=-5,
+ max_value=5,
+ step=0.1,
+ precision=1,
+ label="$I$",
+ )
+ matrix
+ return
+
+def __():
+ matrix.value
+ return
+```
+
+///
+
+::: marimo.ui.matrix
diff --git a/docs/api/inputs/vector.md b/docs/api/inputs/vector.md
new file mode 100644
index 0000000000..fce081a982
--- /dev/null
+++ b/docs/api/inputs/vector.md
@@ -0,0 +1,27 @@
+# Vector
+
+/// marimo-embed
+
+```python
+def __():
+ vector = mo.ui.vector(
+ [1, 0, 0, 0, 0],
+ min_value=-5,
+ max_value=5,
+ step=0.1,
+ precision=1,
+ label="$\\vec{v}$",
+ )
+ vector
+ return
+
+def __():
+ vector.value
+ return
+```
+
+///
+
+::: marimo.ui.vector
diff --git a/docs/examples/index.md b/docs/examples/index.md
index 5057ada91f..3484d433f3 100644
--- a/docs/examples/index.md
+++ b/docs/examples/index.md
@@ -295,6 +295,18 @@ guide](../guides/interactivity.md) for rules governing how UI elements work.
<a href="../api/inputs/chat.md"><img src="/_static/example-thumbs/chat.png" /></a>
+- 🔢 [**Matrix**](../api/inputs/matrix.md)
+
+ ---
+
+ <a href="../api/inputs/matrix.md"><img src="/_static/example-thumbs/matrix.png" /></a>
+
+- 📐 [**Vector**](../api/inputs/vector.md)
+
+ ---
+
+ <a href="../api/inputs/vector.md"><img src="/_static/example-thumbs/vector.png" /></a>
+
</div>
### Composite input elements
diff --git a/examples/ui/matrix.py b/examples/ui/matrix.py
new file mode 100644
index 0000000000..21450c7bb8
--- /dev/null
+++ b/examples/ui/matrix.py
@@ -0,0 +1,35 @@
+import marimo
+
+__generated_with = "0.19.7"
+app = marimo.App(width="medium")
+
+
+def _():
+ import marimo as mo
+
+ return (mo,)
+
+
+def _(mo):
+ matrix = mo.ui.matrix(
+ [[1, 0, 0], [0, 1, 0], [0, 0, 1]],
+ min_value=-5,
+ max_value=5,
+ step=0.1,
+ precision=1,
+ label="$I$",
+ )
+ matrix
+ return (matrix,)
+
+
+def _(matrix):
+ matrix.value
+ return
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/examples/ui/vector.py b/examples/ui/vector.py
new file mode 100644
index 0000000000..0831320a9d
--- /dev/null
+++ b/examples/ui/vector.py
@@ -0,0 +1,41 @@
+import marimo
+
+__generated_with = "0.19.11"
+app = marimo.App()
+
+
+def _():
+ import marimo as mo
+ import numpy as np
+
+ return mo, np
+
+
+def _(mo):
+ hstack = lambda x: mo.hstack(x, justify="start")
+ return (hstack,)
+
+
+def _(mo):
+ v1 = mo.ui.vector([1, 1, 1])
+ v2 = mo.ui.vector([1, 1, 1], transpose=True)
+ return v1, v2
+
+
+def _(mo, np, v1, v2):
+ v3 = mo.ui.matrix(np.outer(v1.value, v2.value))
+ return (v3,)
+
+
+def _(hstack, v1, v2, v3):
+ hstack([v1, v2, "=", v3])
+ return
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/frontend/src/plugins/impl/MatrixPlugin.tsx b/frontend/src/plugins/impl/MatrixPlugin.tsx
new file mode 100644
index 0000000000..d3d3cbc85e
--- /dev/null
+++ b/frontend/src/plugins/impl/MatrixPlugin.tsx
@@ -0,0 +1,277 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+import { type JSX, useCallback, useEffect, useRef, useState } from "react";
+import { z } from "zod";
+import { cn } from "@/utils/cn";
+import type { IPlugin, IPluginProps, Setter } from "../types";
+import { Labeled } from "./common/labeled";
+import matrixCss from "./matrix.css?inline";
+
+type T = number[][];
+
+interface Data {
+ label: string | null;
+ minValue?: number[][] | null;
+ maxValue?: number[][] | null;
+ step: number[][];
+ precision: number;
+ rowLabels?: string[] | null;
+ columnLabels?: string[] | null;
+ symmetric: boolean;
+ debounce: boolean;
+ scientific: boolean;
+ disabled: boolean[][];
+}
+
+export class MatrixPlugin implements IPlugin<T, Data> {
+ tagName = "marimo-matrix";
+
+ cssStyles = [matrixCss];
+
+ validator = z.object({
+ initialValue: z.array(z.array(z.number())),
+ label: z.string().nullable(),
+ minValue: z.array(z.array(z.number())).nullish(),
+ maxValue: z.array(z.array(z.number())).nullish(),
+ step: z.array(z.array(z.number())),
+ precision: z.number(),
+ rowLabels: z.array(z.string()).nullish(),
+ columnLabels: z.array(z.string()).nullish(),
+ symmetric: z.boolean(),
+ debounce: z.boolean().default(false),
+ scientific: z.boolean(),
+ disabled: z.array(z.array(z.boolean())),
+ });
+
+ render(props: IPluginProps<T, Data>): JSX.Element {
+ return (
+ <MatrixComponent
+ {...props.data}
+ value={props.value}
+ setValue={props.setValue}
+ />
+ );
+ }
+}
+
+const PIXELS_PER_STEP = 10;
+
+interface MatrixComponentProps extends Data {
+ value: T;
+ setValue: Setter<T>;
+}
+
+const MatrixComponent = ({
+ value,
+ setValue,
+ label,
+ minValue,
+ maxValue,
+ step,
+ precision,
+ rowLabels,
+ columnLabels,
+ symmetric,
+ debounce,
+ scientific,
+ disabled,
+}: MatrixComponentProps): JSX.Element => {
+ const dragState = useRef<{
+ row: number;
+ col: number;
+ startX: number;
+ startValue: number;
+ } | null>(null);
+ const [activeCell, setActiveCell] = useState<{
+ row: number;
+ col: number;
+ } | null>(null);
+
+ // Local display value – always tracks the latest visual state.
+ // When debounce is true we update this locally during drag and only
+ // call setValue on pointer-up.
+ const [internalValue, setInternalValue] = useState(value);
+ useEffect(() => {
+ setInternalValue(value);
+ }, [value]);
+
+ const formatValue = (val: number) =>
+ scientific ? val.toExponential(precision) : val.toFixed(precision);
+
+ const clampValue = useCallback(
+ (val: number, row: number, col: number): number => {
+ let clamped = val;
+ if (minValue != null) {
+ clamped = Math.max(clamped, minValue[row][col]);
+ }
+ if (maxValue != null) {
+ clamped = Math.min(clamped, maxValue[row][col]);
+ }
+ return clamped;
+ },
+ [minValue, maxValue],
+ );
+
+ const handlePointerDown = useCallback(
+ (e: React.PointerEvent, row: number, col: number) => {
+ if (disabled[row][col] || !(e.target instanceof Element)) {
+ return;
+ }
+ e.preventDefault();
+ e.target.setPointerCapture(e.pointerId);
+ dragState.current = {
+ row,
+ col,
+ startX: e.clientX,
+ startValue: internalValue[row][col],
+ };
+ setActiveCell({ row, col });
+ },
+ [disabled, internalValue],
+ );
+
+ const handlePointerMove = useCallback(
+ (e: React.PointerEvent) => {
+ const state = dragState.current;
+ if (!state) {
+ return;
+ }
+ const { row, col, startX, startValue } = state;
+ const dx = e.clientX - startX;
+ const cellStep = step[row][col];
+ const steps = Math.round(dx / PIXELS_PER_STEP);
+ const rawValue = startValue + steps * cellStep;
+ const newValue = clampValue(rawValue, row, col);
+
+ if (newValue !== internalValue[row][col]) {
+ const copy = internalValue.map((r) => [...r]);
+ copy[row][col] = newValue;
+ if (symmetric && row !== col) {
+ copy[col][row] = newValue;
+ }
+ setInternalValue(copy);
+ if (!debounce) {
+ setValue(copy);
+ }
+ }
+ },
+ [step, clampValue, internalValue, symmetric, debounce, setValue],
+ );
+
+ const handlePointerUp = useCallback(() => {
+ if (debounce && dragState.current) {
+ setValue(internalValue);
+ }
+ dragState.current = null;
+ setActiveCell(null);
+ }, [debounce, internalValue, setValue]);
+
+ const handleKeyDown = useCallback(
+ (e: React.KeyboardEvent, row: number, col: number) => {
+ if (e.key === "ArrowUp" || e.key === "ArrowDown") {
+ if (disabled[row][col]) {
+ return;
+ }
+ e.preventDefault();
+ const cellStep = step[row][col];
+ const delta = e.key === "ArrowUp" ? cellStep : -cellStep;
+ const newValue = clampValue(internalValue[row][col] + delta, row, col);
+
+ if (newValue !== internalValue[row][col]) {
+ const copy = internalValue.map((r) => [...r]);
+ copy[row][col] = newValue;
+ if (symmetric && row !== col) {
+ copy[col][row] = newValue;
+ }
+ setInternalValue(copy);
+ setValue(copy);
+ }
+ }
+ },
+ [disabled, step, internalValue, clampValue, symmetric, setValue],
+ );
+
+ const hasRowLabels = rowLabels != null && rowLabels.length > 0;
+ const hasColumnLabels = columnLabels != null && columnLabels.length > 0;
+
+ const numRows = internalValue.length;
+ const numCols = internalValue[0]?.length ?? 0;
+
+ return (
+ <Labeled label={label} align="top" className="items-center">
+ <div
+ className="relative inline-block"
+ data-testid="marimo-plugin-matrix"
+ onPointerMove={handlePointerMove}
+ onPointerUp={handlePointerUp}
+ onPointerCancel={handlePointerUp}
+ >
+ <table
+ className="font-mono text-sm tabular-nums select-none border-separate border-spacing-0"
+ role="group"
+ aria-label={label || "Matrix"}
+ >
+ {hasColumnLabels && (
+ <thead>
+ <tr>
+ {hasRowLabels && <th />}
+ {columnLabels.map((lbl, j) => (
+ <th
+ key={j}
+ className="text-center text-sm font-medium text-foreground px-2 pb-1"
+ >
+ {lbl}
+ </th>
+ ))}
+ </tr>
+ </thead>
+ )}
+ <tbody>
+ {internalValue.map((row, i) => (
+ <tr key={i}>
+ {hasRowLabels && (
+ <th className="text-right text-sm font-medium text-foreground pr-3 h-8">
+ {rowLabels[i]}
+ </th>
+ )}
+ {row.map((cellValue, j) => {
+ const isDisabled = disabled[i][j];
+ const isActive =
+ activeCell?.row === i && activeCell?.col === j;
+ const rowLabel = rowLabels?.[i] ?? `Row ${i + 1}`;
+ const colLabel = columnLabels?.[j] ?? `Column ${j + 1}`;
+ return (
+ <td
+ key={j}
+ className={cn(
+ "relative text-right min-w-14 h-8 px-2 transition-colors touch-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none",
+ isDisabled
+ ? "cursor-default text-muted-foreground"
+ : "cursor-ew-resize text-[var(--link)] hover:bg-accent",
+ isActive && "bg-accent",
+ j === 0 && "bracket-l",
+ j === numCols - 1 && "bracket-r",
+ i === 0 && "bracket-t",
+ i === numRows - 1 && "bracket-b",
+ )}
+ tabIndex={isDisabled ? -1 : 0}
+ aria-label={`${rowLabel}, ${colLabel}`}
+ aria-valuenow={cellValue}
+ aria-valuemin={minValue?.[i]?.[j]}
+ aria-valuemax={maxValue?.[i]?.[j]}
+ aria-disabled={isDisabled || undefined}
+ onPointerDown={(e) => handlePointerDown(e, i, j)}
+ onKeyDown={(e) => handleKeyDown(e, i, j)}
+ data-testid={`matrix-cell-${i}-${j}`}
+ >
+ {formatValue(cellValue)}
+ </td>
+ );
+ })}
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ </div>
+ </Labeled>
+ );
+};
diff --git a/frontend/src/plugins/impl/__tests__/MatrixPlugin.test.tsx b/frontend/src/plugins/impl/__tests__/MatrixPlugin.test.tsx
new file mode 100644
index 0000000000..a050615883
--- /dev/null
+++ b/frontend/src/plugins/impl/__tests__/MatrixPlugin.test.tsx
@@ -0,0 +1,415 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+
+import { fireEvent, render } from "@testing-library/react";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import type { IPluginProps } from "../../types";
+import { MatrixPlugin } from "../MatrixPlugin";
+
+type PluginData = ReturnType<MatrixPlugin["validator"]["parse"]>;
+
+function makeProps(
+ overrides: Partial<IPluginProps<number[][], PluginData>> = {},
+): IPluginProps<number[][], PluginData> {
+ return {
+ host: document.createElement("div"),
+ value: [
+ [1, 2],
+ [3, 4],
+ ],
+ setValue: vi.fn(),
+ data: {
+ initialValue: [
+ [1, 2],
+ [3, 4],
+ ],
+ label: null,
+ minValue: null,
+ maxValue: null,
+ step: [
+ [1, 1],
+ [1, 1],
+ ],
+ precision: 1,
+ rowLabels: null,
+ columnLabels: null,
+ symmetric: false,
+ debounce: false,
+ scientific: false,
+ disabled: [
+ [false, false],
+ [false, false],
+ ],
+ },
+ functions: {},
+ ...overrides,
+ };
+}
+
+beforeEach(() => {
+ // jsdom doesn't implement pointer capture
+ Element.prototype.setPointerCapture = vi.fn();
+ Element.prototype.releasePointerCapture = vi.fn();
+
+ // jsdom's PointerEvent doesn't properly inherit MouseEvent properties
+ // like clientX. Polyfill it so fireEvent.pointerDown/Move/Up work.
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ (globalThis as any).PointerEvent = class PointerEvent extends MouseEvent {
+ readonly pointerId: number;
+ constructor(type: string, init: PointerEventInit = {}) {
+ super(type, init);
+ this.pointerId = init.pointerId ?? 0;
+ }
+ };
+});
+
+describe("MatrixPlugin", () => {
+ it("renders correct number of cells", () => {
+ const plugin = new MatrixPlugin();
+ const props = makeProps();
+ const { getAllByTestId } = render(plugin.render(props));
+
+ const cells = getAllByTestId(/^matrix-cell-/);
+ expect(cells).toHaveLength(4);
+ });
+
+ it("displays values with correct precision", () => {
+ const plugin = new MatrixPlugin();
+ const props = makeProps({
+ value: [
+ [1.5, 2.123],
+ [3, 4.9],
+ ],
+ data: {
+ ...makeProps().data,
+ precision: 2,
+ },
+ });
+ const { getByTestId } = render(plugin.render(props));
+
+ expect(getByTestId("matrix-cell-0-0").textContent).toBe("1.50");
+ expect(getByTestId("matrix-cell-0-1").textContent).toBe("2.12");
+ expect(getByTestId("matrix-cell-1-0").textContent).toBe("3.00");
+ expect(getByTestId("matrix-cell-1-1").textContent).toBe("4.90");
+ });
+
+ it("renders disabled cells with aria-disabled", () => {
+ const plugin = new MatrixPlugin();
+ const props = makeProps({
+ data: {
+ ...makeProps().data,
+ disabled: [
+ [true, false],
+ [false, true],
+ ],
+ },
+ });
+ const { getByTestId } = render(plugin.render(props));
+
+ expect(getByTestId("matrix-cell-0-0").getAttribute("aria-disabled")).toBe(
+ "true",
+ );
+ expect(getByTestId("matrix-cell-0-1").hasAttribute("aria-disabled")).toBe(
+ false,
+ );
+ expect(getByTestId("matrix-cell-1-0").hasAttribute("aria-disabled")).toBe(
+ false,
+ );
+ expect(getByTestId("matrix-cell-1-1").getAttribute("aria-disabled")).toBe(
+ "true",
+ );
+ });
+
+ it("renders row labels", () => {
+ const plugin = new MatrixPlugin();
+ const props = makeProps({
+ data: {
+ ...makeProps().data,
+ rowLabels: ["Row A", "Row B"],
+ },
+ });
+ const { getByText } = render(plugin.render(props));
+
+ expect(getByText("Row A")).toBeDefined();
+ expect(getByText("Row B")).toBeDefined();
+ });
+
+ it("renders column labels", () => {
+ const plugin = new MatrixPlugin();
+ const props = makeProps({
+ data: {
+ ...makeProps().data,
+ columnLabels: ["Col X", "Col Y"],
+ },
+ });
+ const { getByText } = render(plugin.render(props));
+
+ expect(getByText("Col X")).toBeDefined();
+ expect(getByText("Col Y")).toBeDefined();
+ });
+
+ it("renders a 3x3 matrix", () => {
+ const plugin = new MatrixPlugin();
+ const props = makeProps({
+ value: [
+ [1, 0, 0],
+ [0, 1, 0],
+ [0, 0, 1],
+ ],
+ data: {
+ ...makeProps().data,
+ step: [
+ [1, 1, 1],
+ [1, 1, 1],
+ [1, 1, 1],
+ ],
+ disabled: [
+ [false, false, false],
+ [false, false, false],
+ [false, false, false],
+ ],
+ },
+ });
+ const { getAllByTestId } = render(plugin.render(props));
+
+ const cells = getAllByTestId(/^matrix-cell-/);
+ expect(cells).toHaveLength(9);
+ });
+
+ it("validates with zod schema", () => {
+ const plugin = new MatrixPlugin();
+ const result = plugin.validator.safeParse({
+ initialValue: [
+ [1, 2],
+ [3, 4],
+ ],
+ label: "test",
+ minValue: null,
+ maxValue: null,
+ step: [
+ [1, 1],
+ [1, 1],
+ ],
+ precision: 1,
+ rowLabels: null,
+ columnLabels: null,
+ symmetric: false,
+ scientific: false,
+ disabled: [
+ [false, false],
+ [false, false],
+ ],
+ });
+ expect(result.success).toBe(true);
+ });
+
+ it("displays values in scientific notation", () => {
+ const plugin = new MatrixPlugin();
+ const props = makeProps({
+ value: [
+ [0.00153, 1234567],
+ [0, -0.042],
+ ],
+ data: {
+ ...makeProps().data,
+ scientific: true,
+ precision: 2,
+ },
+ });
+ const { getByTestId } = render(plugin.render(props));
+
+ expect(getByTestId("matrix-cell-0-0").textContent).toBe("1.53e-3");
+ expect(getByTestId("matrix-cell-0-1").textContent).toBe("1.23e+6");
+ expect(getByTestId("matrix-cell-1-0").textContent).toBe("0.00e+0");
+ expect(getByTestId("matrix-cell-1-1").textContent).toBe("-4.20e-2");
+ });
+
+ it("drag adjusts cell value", () => {
+ const plugin = new MatrixPlugin();
+ const setValueMock = vi.fn();
+ const props = makeProps({
+ value: [
+ [0, 0],
+ [0, 0],
+ ],
+ setValue: setValueMock,
+ });
+ const { getByTestId } = render(plugin.render(props));
+ const cell = getByTestId("matrix-cell-0-0");
+ const container = getByTestId("marimo-plugin-matrix");
+
+ // Pointer down on cell (0,0), then move 30px right = 3 steps
+ fireEvent.pointerDown(cell, { clientX: 100, pointerId: 1 });
+ fireEvent.pointerMove(container, { clientX: 130 });
+ fireEvent.pointerUp(container);
+
+ expect(setValueMock).toHaveBeenCalledWith([
+ [3, 0],
+ [0, 0],
+ ]);
+ });
+
+ it("symmetric mode mirrors value to transpose cell", () => {
+ const plugin = new MatrixPlugin();
+ const setValueMock = vi.fn();
+ const props = makeProps({
+ value: [
+ [0, 0],
+ [0, 0],
+ ],
+ setValue: setValueMock,
+ data: {
+ ...makeProps().data,
+ symmetric: true,
+ },
+ });
+ const { getByTestId } = render(plugin.render(props));
+ const cell = getByTestId("matrix-cell-0-1");
+ const container = getByTestId("marimo-plugin-matrix");
+
+ fireEvent.pointerDown(cell, { clientX: 100, pointerId: 1 });
+ fireEvent.pointerMove(container, { clientX: 120 }); // 2 steps
+ fireEvent.pointerUp(container);
+
+ // Cell (0,1) and (1,0) should both be 2
+ expect(setValueMock).toHaveBeenCalledWith([
+ [0, 2],
+ [2, 0],
+ ]);
+ });
+
+ it("ArrowUp increments cell value", () => {
+ const plugin = new MatrixPlugin();
+ const setValueMock = vi.fn();
+ const props = makeProps({
+ value: [
+ [5, 0],
+ [0, 0],
+ ],
+ setValue: setValueMock,
+ });
+ const { getByTestId } = render(plugin.render(props));
+
+ fireEvent.keyDown(getByTestId("matrix-cell-0-0"), { key: "ArrowUp" });
+
+ expect(setValueMock).toHaveBeenCalledWith([
+ [6, 0],
+ [0, 0],
+ ]);
+ });
+
+ it("ArrowDown decrements cell value", () => {
+ const plugin = new MatrixPlugin();
+ const setValueMock = vi.fn();
+ const props = makeProps({
+ value: [
+ [5, 0],
+ [0, 0],
+ ],
+ setValue: setValueMock,
+ });
+ const { getByTestId } = render(plugin.render(props));
+
+ fireEvent.keyDown(getByTestId("matrix-cell-0-0"), { key: "ArrowDown" });
+
+ expect(setValueMock).toHaveBeenCalledWith([
+ [4, 0],
+ [0, 0],
+ ]);
+ });
+
+ it("disabled cells ignore pointer and keyboard input", () => {
+ const plugin = new MatrixPlugin();
+ const setValueMock = vi.fn();
+ const props = makeProps({
+ value: [
+ [5, 0],
+ [0, 0],
+ ],
+ setValue: setValueMock,
+ data: {
+ ...makeProps().data,
+ disabled: [
+ [true, false],
+ [false, false],
+ ],
+ },
+ });
+ const { getByTestId } = render(plugin.render(props));
+ const cell = getByTestId("matrix-cell-0-0");
+ const container = getByTestId("marimo-plugin-matrix");
+
+ // Keyboard
+ fireEvent.keyDown(cell, { key: "ArrowUp" });
+ expect(setValueMock).not.toHaveBeenCalled();
+
+ // Drag
+ fireEvent.pointerDown(cell, { clientX: 100, pointerId: 1 });
+ fireEvent.pointerMove(container, { clientX: 130 });
+ fireEvent.pointerUp(container);
+ expect(setValueMock).not.toHaveBeenCalled();
+ });
+
+ it("clamps values to min/max bounds", () => {
+ const plugin = new MatrixPlugin();
+ const setValueMock = vi.fn();
+ const props = makeProps({
+ value: [
+ [5, 0],
+ [0, 0],
+ ],
+ setValue: setValueMock,
+ data: {
+ ...makeProps().data,
+ minValue: [
+ [0, 0],
+ [0, 0],
+ ],
+ maxValue: [
+ [6, 10],
+ [10, 10],
+ ],
+ },
+ });
+ const { getByTestId } = render(plugin.render(props));
+ const cell = getByTestId("matrix-cell-0-0");
+ const container = getByTestId("marimo-plugin-matrix");
+
+ // Try to drag far right (would be +10 without clamping)
+ fireEvent.pointerDown(cell, { clientX: 100, pointerId: 1 });
+ fireEvent.pointerMove(container, { clientX: 200 });
+ fireEvent.pointerUp(container);
+
+ // Should be clamped to max of 6
+ expect(setValueMock).toHaveBeenCalledWith([
+ [6, 0],
+ [0, 0],
+ ]);
+ });
+
+ it("sets aria attributes on cells", () => {
+ const plugin = new MatrixPlugin();
+ const props = makeProps({
+ data: {
+ ...makeProps().data,
+ rowLabels: ["x", "y"],
+ columnLabels: ["a", "b"],
+ minValue: [
+ [0, 0],
+ [0, 0],
+ ],
+ maxValue: [
+ [10, 10],
+ [10, 10],
+ ],
+ },
+ });
+ const { getByTestId } = render(plugin.render(props));
+ const cell = getByTestId("matrix-cell-0-1");
+
+ expect(cell.getAttribute("aria-label")).toBe("x, b");
+ expect(cell.getAttribute("aria-valuenow")).toBe("2");
+ expect(cell.getAttribute("aria-valuemin")).toBe("0");
+ expect(cell.getAttribute("aria-valuemax")).toBe("10");
+ expect(cell.getAttribute("tabindex")).toBe("0");
+ });
+});
diff --git a/frontend/src/plugins/impl/matrix.css b/frontend/src/plugins/impl/matrix.css
new file mode 100644
index 0000000000..90904a9262
--- /dev/null
+++ b/frontend/src/plugins/impl/matrix.css
@@ -0,0 +1,45 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+
+/* Left bracket — vertical line + corner ticks via ::before */
+td.bracket-l::before {
+ content: "";
+ position: absolute;
+ top: 0;
+ bottom: 0;
+ left: -4px;
+ width: 0;
+ border-left: 2px solid var(--foreground);
+ pointer-events: none;
+}
+td.bracket-l.bracket-t::before {
+ top: -1px;
+ width: 8px;
+ border-top: 2px solid var(--foreground);
+}
+td.bracket-l.bracket-b::before {
+ bottom: -1px;
+ width: 8px;
+ border-bottom: 2px solid var(--foreground);
+}
+
+/* Right bracket — vertical line + corner ticks via ::after */
+td.bracket-r::after {
+ content: "";
+ position: absolute;
+ top: 0;
+ bottom: 0;
+ right: -4px;
+ width: 0;
+ border-right: 2px solid var(--foreground);
+ pointer-events: none;
+}
+td.bracket-r.bracket-t::after {
+ top: -1px;
+ width: 8px;
+ border-top: 2px solid var(--foreground);
+}
+td.bracket-r.bracket-b::after {
+ bottom: -1px;
+ width: 8px;
+ border-bottom: 2px solid var(--foreground);
+}
diff --git a/frontend/src/plugins/plugins.ts b/frontend/src/plugins/plugins.ts
index 88d6d09f3e..6edc406c3e 100644
--- a/frontend/src/plugins/plugins.ts
+++ b/frontend/src/plugins/plugins.ts
@@ -22,6 +22,7 @@ import { DataFramePlugin } from "./impl/data-frames/DataFramePlugin";
import { FileBrowserPlugin } from "./impl/FileBrowserPlugin";
import { FileUploadPlugin } from "./impl/FileUploadPlugin";
import { FormPlugin } from "./impl/FormPlugin";
+import { MatrixPlugin } from "./impl/MatrixPlugin";
import { MicrophonePlugin } from "./impl/MicrophonePlugin";
import { MultiselectPlugin } from "./impl/MultiselectPlugin";
import { NumberPlugin } from "./impl/NumberPlugin";
@@ -67,6 +68,7 @@ export const UI_PLUGINS: IPlugin<any, unknown>[] = [
new FileUploadPlugin(),
FileBrowserPlugin,
FormPlugin,
+ new MatrixPlugin(),
new MicrophonePlugin(),
new MultiselectPlugin(),
new NumberPlugin(),
diff --git a/marimo/_plugins/ui/__init__.py b/marimo/_plugins/ui/__init__.py
index 45ac00d982..b65d796e8b 100644
--- a/marimo/_plugins/ui/__init__.py
+++ b/marimo/_plugins/ui/__init__.py
@@ -25,6 +25,7 @@ __all__ = [
"file_browser",
"file",
"form",
+ "matrix",
"microphone",
"multiselect",
"number",
@@ -40,6 +41,7 @@ __all__ = [
"tabs",
"text_area",
"text",
+ "vector",
]
from marimo._plugins.ui._impl.altair_chart import altair_chart
@@ -76,6 +78,7 @@ from marimo._plugins.ui._impl.input import (
text,
text_area,
)
+from marimo._plugins.ui._impl.matrix import matrix
from marimo._plugins.ui._impl.microphone import microphone
from marimo._plugins.ui._impl.plotly import plotly
from marimo._plugins.ui._impl.refresh import refresh
@@ -83,3 +86,4 @@ from marimo._plugins.ui._impl.run_button import run_button
from marimo._plugins.ui._impl.switch import switch
from marimo._plugins.ui._impl.table import table
from marimo._plugins.ui._impl.tabs import tabs
+from marimo._plugins.ui._impl.vector import vector
diff --git a/marimo/_plugins/ui/_impl/matrix.py b/marimo/_plugins/ui/_impl/matrix.py
new file mode 100644
index 0000000000..21617b4855
--- /dev/null
+++ b/marimo/_plugins/ui/_impl/matrix.py
@@ -0,0 +1,399 @@
+# Copyright 2026 Marimo. All rights reserved.
+from __future__ import annotations
+
+from typing import (
+ TYPE_CHECKING,
+ Any,
+ Final,
+)
+
+from marimo._output.rich_help import mddoc
+from marimo._plugins.ui._core.ui_element import UIElement
+
+if TYPE_CHECKING:
+ from numpy.typing import ArrayLike
+
+
+Numeric = int | float
+
+
+def _broadcast(
+ name: str,
+ param: Any,
+ rows: int,
+ cols: int,
+) -> list[list[Any]]:
+ """Broadcast a scalar, nested list, or array-like to a rows x cols matrix.
+
+ *convert* is applied to every cell (e.g. `float` or `bool`).
+ """
+ if hasattr(param, "tolist"):
+ param = param.tolist()
+
+ if not isinstance(param, list):
+ return [[param] * cols for _ in range(rows)]
+
+ if len(param) != rows:
+ raise ValueError(f"`{name}` has {len(param)} rows but expected {rows}")
+
+ for i, row in enumerate(param):
+ if not isinstance(row, (list, tuple)):
+ raise ValueError(
+ f"`{name}` row {i} must be a list, got {type(row)}"
+ )
+ if len(row) != cols:
+ raise ValueError(
+ f"`{name}` row {i} has {len(row)} columns but expected {cols}"
+ )
+ for j, cell in enumerate(row):
+ if isinstance(cell, (list, tuple)):
+ raise ValueError(
+ f"`{name}` must be 2D, but found a nested "
+ f"sequence at position [{i}][{j}]"
+ )
+ return param
+
+
+def _to_nested_list(
+ value: list[list[Numeric]] | ArrayLike,
+) -> list[list[Numeric]]:
+ """Parse and validate initial matrix data into a nested list.
+
+ Accepts a nested list of numbers or a numpy array-like with `.tolist()`.
+ Rejects empty, non-2D, or ragged inputs.
+ """
+ if hasattr(value, "tolist"):
+ value = value.tolist()
+
+ if not isinstance(value, list):
+ raise ValueError(
+ f"`value` must be a list of lists or array-like, got {type(value)}"
+ )
+
+ if not value:
+ raise ValueError("`value` must be non-empty")
+
+ first = value[0]
+ if not isinstance(first, (list, tuple)) or not first:
+ raise ValueError(
+ f"`value` must contain non-empty lists, but row 0 is {first!r}"
+ )
+ return _broadcast("value", value, len(value), len(first))
+
+
+def _decimal_places(x: Numeric) -> int:
+ """Count decimal places needed in fixed notation."""
+ if isinstance(x, int) or x == int(x):
+ return 0
+ s = repr(x)
+ if "e" in s or "E" in s:
+ parts = s.lower().split("e")
+ exp = int(parts[1])
+ mantissa_dec = len(parts[0].split(".")[1]) if "." in parts[0] else 0
+ return max(0, mantissa_dec - exp)
+ if "." in s:
+ return len(s.split(".")[1])
+ return 0
+
+
+def _mantissa_decimal_places(x: Numeric) -> int:
+ """Count decimal places needed in the mantissa for scientific notation.
+
+ For example, `0.00153` → `1.53e-3` → 2 mantissa places,
+ while `1e-8` → `1e-8` → 0 mantissa places.
+ """
+ if isinstance(x, int):
+ # Strip trailing zeros: 1234000 → 1.234e6 → 3 places
+ if x == 0:
+ return 0
+ s = str(abs(x)).rstrip("0")
+ return max(0, len(s) - 1)
+ if x == 0.0:
+ return 0
+ # Format with enough mantissa digits, then strip trailing zeros
+ s = f"{x:.15e}" # e.g. "1.530000000000000e-03"
+ mantissa = s.split("e")[0].rstrip("0").rstrip(".")
+ if "." in mantissa:
+ return len(mantissa.split(".")[1])
+ return 0
+
+
+def _infer_precision(
+ data: list[list[Numeric]],
+ step_val: list[list[Any]],
+ scientific: bool,
+) -> int:
+ """Choose a display precision based on the data values and step sizes.
+
+ When *scientific* is True, counts mantissa decimal places (e.g.
+ `0.00153` needs 2 for `1.53e-3`). Otherwise counts total
+ decimal places in fixed notation (`0.00153` needs 5).
+ """
+ counter = _mantissa_decimal_places if scientific else _decimal_places
+ best = 0
+ for row in data:
+ for v in row:
+ best = max(best, counter(v))
+ for row in step_val:
+ for v in row:
+ best = max(best, counter(v))
+ return best
+
+
+def _validate_and_build_args(
+ data: list[list[Numeric]],
+ *,
+ min_val: list[list[Numeric]] | None,
+ max_val: list[list[Numeric]] | None,
+ step_val: list[list[Any]],
+ disabled_val: list[list[Any]],
+ symmetric: bool,
+ scientific: bool,
+ precision: int | None,
+ row_labels: list[str] | None,
+ column_labels: list[str] | None,
+ debounce: bool,
+) -> dict[str, Any]:
+ """Validate matrix parameters and return the args dict for UIElement."""
+ rows = len(data)
+ cols = len(data[0])
+
+ if precision is None:
+ precision = _infer_precision(data, step_val, scientific)
+
+ # Validate per-cell constraints in a single pass
+ for i in range(rows):
+ for j in range(cols):
+ if step_val[i][j] <= 0:
+ raise ValueError(
+ f"`step` must be positive, got {step_val[i][j]} "
+ f"at position [{i}][{j}]"
+ )
+ if min_val is not None and max_val is not None:
+ if min_val[i][j] >= max_val[i][j]:
+ raise ValueError(
+ f"`min_value` ({min_val[i][j]}) must be less "
+ f"than `max_value` ({max_val[i][j]}) at "
+ f"position [{i}][{j}]"
+ )
+ if min_val is not None and data[i][j] < min_val[i][j]:
+ raise ValueError(
+ f"Initial value {data[i][j]} at [{i}][{j}] is "
+ f"less than min_value {min_val[i][j]}"
+ )
+ if max_val is not None and data[i][j] > max_val[i][j]:
+ raise ValueError(
+ f"Initial value {data[i][j]} at [{i}][{j}] is "
+ f"greater than max_value {max_val[i][j]}"
+ )
+
+ # Validate label lengths
+ if row_labels is not None and len(row_labels) != rows:
+ raise ValueError(
+ f"`row_labels` has {len(row_labels)} entries "
+ f"but matrix has {rows} rows"
+ )
+ if column_labels is not None and len(column_labels) != cols:
+ raise ValueError(
+ f"`column_labels` has {len(column_labels)} entries "
+ f"but matrix has {cols} columns"
+ )
+
+ # Validate symmetric requires square matrix with symmetric data
+ if symmetric:
+ if rows != cols:
+ raise ValueError(
+ f"`symmetric` requires a square matrix, but got {rows}x{cols}"
+ )
+ for i in range(rows):
+ for j in range(i + 1, cols):
+ if data[i][j] != data[j][i]:
+ raise ValueError(
+ f"`symmetric` is True but initial data is not "
+ f"symmetric: value[{i}][{j}]={data[i][j]} != "
+ f"value[{j}][{i}]={data[j][i]}"
+ )
+
+ if not isinstance(precision, int) or precision < 0:
+ raise ValueError(
+ f"`precision` must be a non-negative integer, got {precision}"
+ )
+
+ return {
+ "min-value": min_val,
+ "max-value": max_val,
+ "step": step_val,
+ "precision": precision,
+ "row-labels": row_labels,
+ "column-labels": column_labels,
+ "symmetric": symmetric,
+ "debounce": debounce,
+ "scientific": scientific,
+ "disabled": disabled_val,
+ }
+
+
+@mddoc
+class matrix(UIElement[list[list[Numeric]], list[list[Numeric]]]):
+ """An interactive matrix editor.
+
+ A matrix UI element in which each entry is a slider: click and drag
+ horizontally on an entry to increment or decrement its value. The
+ matrix can be configured in many ways, including element-wise
+ bounds, element-wise steps, an element-wise disable mask, and
+ symmetry enforcement.
+
+ Examples:
+ Basic usage:
+
+ ```python
+ mat = mo.ui.matrix([[1, 0], [0, 1]])
+ mat
+ ```
+
+ Access the value in another cell with
+
+ ```python
+ mat.value
+ ```
+
+ You can specify bounds and a step size as well:
+
+ ```python
+ mat = mo.ui.matrix(
+ [[1, 0], [0, 1]],
+ min_value=-10,
+ max_value=10,
+ step=0.5,
+ )
+ ```
+
+ To disable editing of some or all entries, use the disabled argument:
+
+ ```python
+ mat = mo.ui.matrix(
+ [[1, 0], [0, 1]],
+ # Disable editing the diagonal values
+ disabled=[[True, False], [False, True]],
+ )
+ ```
+
+ The value, bounds, step, and disabled arguments can optionally be NumPy
+ arrays, interpreted elementwise.
+
+ ```python
+ import numpy as np
+
+ mat = mo.ui.matrix(np.eye(2))
+ mat
+ ```
+
+ ```
+ np.asarray(mat.value)
+ ```
+
+ Attributes:
+ value (list[list[Numeric]]): The current 2D matrix as a nested list.
+ Use `np.asarray(matrix.value)` to convert to a numpy array.
+
+ Args:
+ value (list[list[Numeric]] | ArrayLike): Initial 2D matrix data.
+ Accepts a nested list of numbers or a numpy array. Rows and
+ columns are inferred from the shape.
+ min_value (Numeric | list[list[Numeric]] | ArrayLike | None, optional):
+ Minimum allowed value. A scalar is broadcast to all cells; a
+ nested list or numpy array sets per-element bounds. None means
+ unbounded. Defaults to None.
+ max_value (Numeric | list[list[Numeric]] | ArrayLike | None, optional):
+ Maximum allowed value. A scalar is broadcast to all cells; a
+ nested list or numpy array sets per-element bounds. None means
+ unbounded. Defaults to None.
+ step (Numeric | list[list[Numeric]] | ArrayLike, optional): Drag
+ increment. A scalar is broadcast to all cells; a nested list
+ or numpy array sets per-element step sizes. Defaults to 1.0.
+ disabled (bool | list[list[bool]] | ArrayLike, optional): Whether
+ cells are disabled. A scalar bool is broadcast to all cells; a
+ nested list or numpy bool array sets a per-element mask.
+ Defaults to False.
+ symmetric (bool, optional): If True, editing cell `[i][j]` also
+ updates cell `[j][i]`. Requires a square matrix. Defaults to False.
+ scientific (bool, optional): If True, display values in scientific
+ notation (e.g., `1.0e-4`). Defaults to False.
+ precision (int | None, optional): Number of decimal places
+ displayed. When None, inferred from the data values and step
+ sizes. Defaults to None.
+ row_labels (list[str] | None, optional): Labels for each row.
+ Defaults to None.
+ column_labels (list[str] | None, optional): Labels for each column.
+ Defaults to None.
+ debounce (bool, optional): If True, value updates are only sent
+ to the backend on mouse-up (pointer release) instead of on
+ every drag movement. Useful when the matrix drives expensive
+ downstream computations. Defaults to False.
+ label (str, optional): Markdown/LaTeX label for the element.
+ Defaults to "".
+ """
+
+ _name: Final[str] = "marimo-matrix"
+
+ def __init__(
+ self,
+ value: list[list[Numeric]] | ArrayLike,
+ *,
+ min_value: Numeric | list[list[Numeric]] | ArrayLike | None = None,
+ max_value: Numeric | list[list[Numeric]] | ArrayLike | None = None,
+ step: Numeric | list[list[Numeric]] | ArrayLike = 1.0,
+ disabled: bool | list[list[bool]] | ArrayLike = False,
+ symmetric: bool = False,
+ scientific: bool = False,
+ precision: int | None = None,
+ row_labels: list[str] | None = None,
+ column_labels: list[str] | None = None,
+ debounce: bool = False,
+ label: str = "",
+ ) -> None:
+ # Convert and validate value
+ data = _to_nested_list(value)
+ rows = len(data)
+ cols = len(data[0])
+
+ # Broadcast params to full matrices
+ min_val = (
+ _broadcast("min_value", min_value, rows, cols)
+ if min_value is not None
+ else None
+ )
+ max_val = (
+ _broadcast("max_value", max_value, rows, cols)
+ if max_value is not None
+ else None
+ )
+ step_val = _broadcast("step", step, rows, cols)
+ disabled_val = _broadcast("disabled", disabled, rows, cols)
+
+ args = _validate_and_build_args(
+ data,
+ min_val=min_val,
+ max_val=max_val,
+ step_val=step_val,
+ disabled_val=disabled_val,
+ symmetric=symmetric,
+ scientific=scientific,
+ precision=precision,
+ row_labels=row_labels,
+ column_labels=column_labels,
+ debounce=debounce,
+ )
+
+ super().__init__(
+ component_name=matrix._name,
+ initial_value=data,
+ label=label,
+ args=args,
+ on_change=None,
+ )
+
+ def _convert_value(
+ self, value: list[list[Numeric]]
+ ) -> list[list[Numeric]]:
+ return value
diff --git a/marimo/_plugins/ui/_impl/vector.py b/marimo/_plugins/ui/_impl/vector.py
new file mode 100644
index 0000000000..068b16dde7
--- /dev/null
+++ b/marimo/_plugins/ui/_impl/vector.py
@@ -0,0 +1,255 @@
+# Copyright 2026 Marimo. All rights reserved.
+from __future__ import annotations
+
+from typing import (
+ TYPE_CHECKING,
+ Any,
+ Final,
+)
+
+from marimo._output.rich_help import mddoc
+from marimo._plugins.ui._core.ui_element import UIElement
+from marimo._plugins.ui._impl.matrix import (
+ Numeric,
+ _broadcast,
+ _validate_and_build_args,
+)
+
+if TYPE_CHECKING:
+ from numpy.typing import ArrayLike
+
+
+def _to_flat_list(
+ value: list[Numeric] | ArrayLike,
+) -> list[Numeric]:
+ """Validate and convert input to a flat list of numbers.
+
+ Accepts a flat list of numbers or a 1D array-like with `.tolist()`.
+ Rejects empty, non-1D, or nested inputs.
+ """
+ if hasattr(value, "tolist"):
+ value = value.tolist()
+
+ if not isinstance(value, list):
+ raise ValueError(
+ f"`value` must be a list or 1D array-like, got {type(value)}"
+ )
+
+ if not value:
+ raise ValueError("`value` must be non-empty")
+
+ for i, v in enumerate(value):
+ if isinstance(v, (list, tuple)):
+ raise ValueError(
+ f"`value` must be 1D, but element {i} is a {type(v).__name__}"
+ )
+
+ return value
+
+
+def _1d_to_2d(
+ name: str,
+ param: Any,
+ transpose: bool,
+) -> Any:
+ """Convert a 1D list param to 2D for matrix consumption.
+
+ Scalars pass through unchanged (they'll be broadcast by `_broadcast`).
+ A 1D list becomes `[[v] for v in param]` (column) or `[param]` (row).
+ """
+ if hasattr(param, "tolist"):
+ param = param.tolist()
+
+ if not isinstance(param, list):
+ # Scalar — let _broadcast handle it
+ return param
+
+ # Must be a flat list at this point
+ for i, v in enumerate(param):
+ if isinstance(v, (list, tuple)):
+ raise ValueError(
+ f"`{name}` must be scalar or 1D, "
+ f"but element {i} is a {type(v).__name__}"
+ )
+
+ if transpose:
+ return [param]
+ else:
+ return [[v] for v in param]
+
+
+@mddoc
+class vector(UIElement[list[list[Numeric]], list[Numeric]]):
+ """An interactive vector editor.
+
+ A vector UI element in which each entry is a slider: click and drag
+ horizontally on an entry to increment or decrement its value. The
+ vector can be configured in many ways, including element-wise
+ bounds, element-wise steps, and an element-wise disable mask.
+
+
+ By default the vector is displayed as a column; pass `transpose=True` for a
+ row vector.
+
+ Examples:
+ Basic usage:
+
+ ```python
+ v = mo.ui.vector([1, 2, 3])
+ v
+ ```
+
+ Access the value in another cell with
+
+ ```python
+ v.value
+ ```
+
+ To create a row vector, use `transpose=True`
+
+ ```python
+ v = mo.ui.vector([1, 2, 3], transpose=True)
+ ```
+
+ You can specify bounds and a step size as well:
+
+ ```python
+ v = mo.ui.vector([1, 2, 3], min_value=-10, max_value=10, step=0.5)
+ ```
+
+ To disable editing of some or all entries, use the disabled argument:
+
+ ```python
+ mat = mo.ui.matrix(
+ [1, 2, 3],
+ # Disable editing of the first entry
+ disabled=[True, False, False],
+ )
+ ```
+
+ The value, bounds, step, and disabled arguments can optionally be NumPy
+ arrays, interpreted elementwise.
+
+ ```python
+ v = mo.ui.vector(np.arange(3))
+ v
+ ```
+
+ ```python
+ np.asaray(v.value)
+ ```
+
+ Attributes:
+ value (list[Numeric]): The current 1D vector as a flat list.
+ Use `np.asarray(vector.value)` to convert to a numpy array.
+
+ Args:
+ value (list[Numeric] | ArrayLike): Initial 1D vector data.
+ Accepts a flat list of numbers or a 1D numpy array.
+ transpose (bool, optional): If True, display as a row vector
+ instead of a column vector. Defaults to False.
+ entry_labels (list[str] | None, optional): Labels for each
+ entry. Mapped to row labels (column vector) or column
+ labels (row vector). Defaults to None.
+ min_value (Numeric | list[Numeric] | ArrayLike | None, optional):
+ Minimum allowed value. A scalar is broadcast to all entries;
+ a list sets per-entry bounds. Defaults to None.
+ max_value (Numeric | list[Numeric] | ArrayLike | None, optional):
+ Maximum allowed value. A scalar is broadcast to all entries;
+ a list sets per-entry bounds. Defaults to None.
+ step (Numeric | list[Numeric] | ArrayLike, optional): Drag
+ increment. A scalar is broadcast; a list sets per-entry
+ steps. Defaults to 1.0.
+ disabled (bool | list[bool] | ArrayLike, optional): Whether
+ entries are disabled. A scalar is broadcast; a list sets
+ a per-entry mask. Defaults to False.
+ scientific (bool, optional): If True, display values in
+ scientific notation. Defaults to False.
+ precision (int | None, optional): Number of decimal places
+ displayed. When None, inferred from the data values and step
+ sizes. Defaults to None.
+ debounce (bool, optional): If True, value updates are only
+ sent on pointer release. Defaults to False.
+ label (str, optional): Markdown/LaTeX label. Defaults to "".
+ """
+
+ _name: Final[str] = "marimo-matrix"
+
+ def __init__(
+ self,
+ value: list[Numeric] | ArrayLike,
+ *,
+ transpose: bool = False,
+ entry_labels: list[str] | None = None,
+ min_value: Numeric | list[Numeric] | ArrayLike | None = None,
+ max_value: Numeric | list[Numeric] | ArrayLike | None = None,
+ step: Numeric | list[Numeric] | ArrayLike = 1.0,
+ disabled: bool | list[bool] | ArrayLike = False,
+ scientific: bool = False,
+ precision: int | None = None,
+ debounce: bool = False,
+ label: str = "",
+ ) -> None:
+ flat = _to_flat_list(value)
+
+ # Convert 1D value → 2D for matrix plugin
+ if transpose:
+ data: list[list[Numeric]] = [flat]
+ else:
+ data = [[v] for v in flat]
+
+ rows = len(data)
+ cols = len(data[0])
+
+ # Convert 1D params → 2D
+ min_2d = _1d_to_2d("min_value", min_value, transpose)
+ max_2d = _1d_to_2d("max_value", max_value, transpose)
+ step_2d = _1d_to_2d("step", step, transpose)
+ disabled_2d = _1d_to_2d("disabled", disabled, transpose)
+
+ # Broadcast to full matrix shape
+ min_val = (
+ _broadcast("min_value", min_2d, rows, cols)
+ if min_value is not None
+ else None
+ )
+ max_val = (
+ _broadcast("max_value", max_2d, rows, cols)
+ if max_value is not None
+ else None
+ )
+ step_val = _broadcast("step", step_2d, rows, cols)
+ disabled_val = _broadcast("disabled", disabled_2d, rows, cols)
+
+ # Map entry_labels to row_labels or column_labels
+ if transpose:
+ row_labels = None
+ column_labels = entry_labels
+ else:
+ row_labels = entry_labels
+ column_labels = None
+
+ args = _validate_and_build_args(
+ data,
+ min_val=min_val,
+ max_val=max_val,
+ step_val=step_val,
+ disabled_val=disabled_val,
+ symmetric=False,
+ scientific=scientific,
+ precision=precision,
+ row_labels=row_labels,
+ column_labels=column_labels,
+ debounce=debounce,
+ )
+
+ super().__init__(
+ component_name=vector._name,
+ initial_value=data,
+ label=label,
+ args=args,
+ on_change=None,
+ )
+
+ def _convert_value(self, value: list[list[Numeric]]) -> list[Numeric]:
+ return [cell for row in value for cell in row]
diff --git a/marimo/_smoke_tests/matrix.py b/marimo/_smoke_tests/matrix.py
new file mode 100644
index 0000000000..821b1fe613
--- /dev/null
+++ b/marimo/_smoke_tests/matrix.py
@@ -0,0 +1,375 @@
+# Copyright 2026 Marimo. All rights reserved.
+
+import marimo
+
+__generated_with = "0.19.11"
+app = marimo.App()
+
+
+def _():
+ import marimo as mo
+
+ return (mo,)
+
+
[email protected](hide_code=True)
+def _(mo):
+ mo.md("""
+ ## Basic matrix (2x2 identity)
+ """)
+ return
+
+
+def _(mo):
+ identity = mo.ui.matrix([[1, 0], [0, 1]], label="Identity")
+ identity
+ return (identity,)
+
+
+def _(identity):
+ identity.value
+ return
+
+
[email protected](hide_code=True)
+def _(mo):
+ mo.md("""
+ ## With bounds, step, and precision
+ """)
+ return
+
+
+def _(mo):
+ bounded = mo.ui.matrix(
+ [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]],
+ min_value=-5,
+ max_value=5,
+ step=0.25,
+ precision=2,
+ label="Bounded ([-5, 5], step=0.25)",
+ )
+ bounded
+ return (bounded,)
+
+
+def _(bounded):
+ bounded.value
+ return
+
+
[email protected](hide_code=True)
+def _(mo):
+ mo.md("""
+ ## With row and column labels
+ """)
+ return
+
+
+def _(mo):
+ labeled = mo.ui.matrix(
+ [[1, 2, 3], [4, 5, 6]],
+ row_labels=["x", "y"],
+ column_labels=["a", "b", "c"],
+ label="Labeled matrix",
+ )
+ labeled
+ return (labeled,)
+
+
+def _(labeled):
+ labeled.value
+ return
+
+
[email protected](hide_code=True)
+def _(mo):
+ mo.md("""
+ ## Symmetric mode (square matrix)
+ """)
+ return
+
+
+def _(mo):
+ sym = mo.ui.matrix(
+ [[1, 0.5, 0], [0.5, 1, 0.3], [0, 0.3, 1]],
+ min_value=-1,
+ max_value=1,
+ step=0.1,
+ precision=1,
+ symmetric=True,
+ label="Symmetric (drag [i,j] to also update [j,i])",
+ )
+ sym
+ return (sym,)
+
+
+def _(sym):
+ sym.value
+ return
+
+
[email protected](hide_code=True)
+def _(mo):
+ mo.md("""
+ ## Per-element disabled mask
+ """)
+ return
+
+
+def _(mo):
+ masked = mo.ui.matrix(
+ [[1, 0, 0], [0, 1, 0], [0, 0, 1]],
+ disabled=[
+ [True, False, False],
+ [False, True, False],
+ [False, False, True],
+ ],
+ label="Diagonal locked",
+ )
+ masked
+ return (masked,)
+
+
+def _(masked):
+ masked.value
+ return
+
+
[email protected](hide_code=True)
+def _(mo):
+ mo.md("""
+ ## NumPy interop
+ """)
+ return
+
+
+def _(mo):
+ import numpy as np
+
+ np_mat = mo.ui.matrix(
+ np.eye(3),
+ step=0.1,
+ precision=1,
+ label="$I$",
+ )
+ np_mat
+ return np, np_mat
+
+
+def _(np, np_mat):
+ arr = np.asarray(np_mat.value)
+ arr
+ return
+
+
[email protected](hide_code=True)
+def _(mo):
+ mo.md("""
+ ## NumPy arrays for bounds and step
+ """)
+ return
+
+
+def _(mo, np):
+ np_bounds = mo.ui.matrix(
+ np.zeros((3, 3)),
+ min_value=np.full((3, 3), -10.0),
+ max_value=np.full((3, 3), 10.0),
+ step=np.full((3, 3), 0.5),
+ precision=1,
+ label="np bounds and step",
+ )
+ np_bounds
+ return (np_bounds,)
+
+
+def _(np, np_bounds):
+ np.asarray(np_bounds.value)
+ return
+
+
[email protected](hide_code=True)
+def _(mo):
+ mo.md("""
+ ## NumPy per-element step (varies by cell)
+ """)
+ return
+
+
+def _(mo, np):
+ step_matrix = np.array([[0.1, 0.5, 1.0], [1.0, 0.5, 0.1], [0.01, 0.01, 0.01]])
+ varying_step = mo.ui.matrix(
+ np.zeros((3, 3)),
+ step=step_matrix,
+ precision=2,
+ label="Per-element step",
+ column_labels=["step=col", "step=mid", "step=fine"],
+ )
+ varying_step
+ return (varying_step,)
+
+
+def _(np, varying_step):
+ np.asarray(varying_step.value)
+ return
+
+
[email protected](hide_code=True)
+def _(mo):
+ mo.md("""
+ ## NumPy disabled mask
+ """)
+ return
+
+
+def _(mo, np):
+ mask = np.eye(4, dtype=bool)
+ np_disabled = mo.ui.matrix(
+ np.arange(16, dtype=float).reshape(4, 4),
+ disabled=mask,
+ precision=0,
+ label=r"$\text{diag}(0, 5, 10, 15) + X$",
+ )
+ np_disabled
+ return (np_disabled,)
+
+
+def _(np, np_disabled):
+ np.asarray(np_disabled.value)
+ return
+
+
[email protected](hide_code=True)
+def _(mo):
+ mo.md("""
+ ## NumPy: asymmetric bounds (different per cell)
+ """)
+ return
+
+
+def _(mo, np):
+ mins = np.array([[0, -5], [-10, -1]])
+ maxs = np.array([[10, 5], [10, 1]])
+ asym = mo.ui.matrix(
+ np.array([[5.0, 0.0], [0.0, 0.0]]),
+ min_value=mins,
+ max_value=maxs,
+ step=0.5,
+ precision=1,
+ row_labels=["row0", "row1"],
+ column_labels=["[0,10]|[-5,5]", "[-10,10]|[-1,1]"],
+ label="Per-cell bounds from numpy",
+ )
+ asym
+ return (asym,)
+
+
+def _(asym, np):
+ np.asarray(asym.value)
+ return
+
+
[email protected](hide_code=True)
+def _(mo):
+ mo.md("""
+ ## Round-trip: numpy in, numpy out
+ """)
+ return
+
+
+def _(mo, np):
+ original = np.random.default_rng(42).uniform(-1, 1, size=(3, 3)).round(2)
+ roundtrip = mo.ui.matrix(
+ original,
+ precision=2,
+ step=0.01,
+ label="Random matrix (edit and check below)",
+ )
+ roundtrip
+ return original, roundtrip
+
+
+def _(np, original, roundtrip):
+ current = np.asarray(roundtrip.value)
+ mo_result = {
+ "original": original,
+ "current": current,
+ "changed": not np.array_equal(original, current),
+ "dtype": current.dtype,
+ "shape": current.shape,
+ }
+ mo_result
+ return
+
+
[email protected](hide_code=True)
+def _(mo):
+ mo.md("""
+ ## Scientific notation
+ """)
+ return
+
+
+def _(mo):
+ sci = mo.ui.matrix(
+ [[0.00153, 1234567], [1e-8, -0.042]],
+ scientific=True,
+ precision=2,
+ step=1e-4,
+ label="Scientific notation",
+ )
+ sci
+ return (sci,)
+
+
+def _(sci):
+ sci.value
+ return
+
+
[email protected](hide_code=True)
+def _(mo):
+ mo.md(r"""
+ ## Debounce
+ """)
+ return
+
+
+def _(mo, np):
+ db = mo.ui.matrix(
+ np.eye(3),
+ precision=2,
+ debounce=True,
+ )
+ db
+ return
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/marimo/_smoke_tests/vector.py b/marimo/_smoke_tests/vector.py
new file mode 100644
index 0000000000..6a022f5d6c
--- /dev/null
+++ b/marimo/_smoke_tests/vector.py
@@ -0,0 +1,195 @@
+# Copyright 2026 Marimo. All rights reserved.
+
+import marimo
+
+__generated_with = "0.19.11"
+app = marimo.App()
+
+
+def _():
+ import marimo as mo
+
+ return (mo,)
+
+
[email protected](hide_code=True)
+def _(mo):
+ mo.md("""
+ ## Basic column vector
+ """)
+ return
+
+
+def _(mo):
+ col = mo.ui.vector([1, 2, 3], precision=2, label="Column vector")
+ col
+ return (col,)
+
+
+def _(col):
+ col.value
+ return
+
+
[email protected](hide_code=True)
+def _(mo):
+ mo.md("""
+ ## Row vector (transposed)
+ """)
+ return
+
+
+def _(mo):
+ row = mo.ui.vector([10, 20, 30], transpose=True, label="Row vector")
+ row
+ return (row,)
+
+
+def _(row):
+ row.value
+ return
+
+
[email protected](hide_code=True)
+def _(mo):
+ mo.md("""
+ ## With bounds and step
+ """)
+ return
+
+
+def _(mo):
+ bounded = mo.ui.vector(
+ [0, 0, 0, 0],
+ min_value=-5,
+ max_value=5,
+ step=0.25,
+ precision=2,
+ label="Bounded ([-5, 5], step=0.25)",
+ )
+ bounded
+ return (bounded,)
+
+
+def _(bounded):
+ bounded.value
+ return
+
+
[email protected](hide_code=True)
+def _(mo):
+ mo.md("""
+ ## With entry labels
+ """)
+ return
+
+
+def _(mo):
+ labeled = mo.ui.vector(
+ [1.0, 0.5, 0.0],
+ entry_labels=["x", "y", "z"],
+ step=0.1,
+ precision=1,
+ label="$v$",
+ )
+ labeled
+ return (labeled,)
+
+
+def _(labeled):
+ labeled.value
+ return
+
+
[email protected](hide_code=True)
+def _(mo):
+ mo.md("""
+ ## NumPy interop
+ """)
+ return
+
+
+def _(mo):
+ import numpy as np
+
+ np_vec = mo.ui.vector(
+ np.zeros(5),
+ step=0.1,
+ precision=1,
+ label=r"$\vec{0}$",
+ )
+ np_vec
+ return np, np_vec
+
+
+def _(np, np_vec):
+ np.asarray(np_vec.value)
+ return
+
+
[email protected](hide_code=True)
+def _(mo):
+ mo.md("""
+ ## Scientific notation
+ """)
+ return
+
+
+def _(mo):
+ sci = mo.ui.vector(
+ [0.00153, 1234567, 1e-8, -0.042],
+ scientific=True,
+ precision=2,
+ step=1e-4,
+ label="Scientific notation",
+ )
+ sci
+ return (sci,)
+
+
+def _(sci):
+ sci.value
+ return
+
+
[email protected](hide_code=True)
+def _(mo):
+ mo.md("""
+ ## Debounce
+ """)
+ return
+
+
+def _(mo):
+ db = mo.ui.vector(
+ [1, 2, 3],
+ precision=2,
+ debounce=True,
+ label="Debounced",
+ )
+ db
+ return (db,)
+
+
+def _(db):
+ db.value
+ return
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/marimo/_tutorials/ui.py b/marimo/_tutorials/ui.py
index bd30cbb09f..f9eb0e4f3f 100644
--- a/marimo/_tutorials/ui.py
+++ b/marimo/_tutorials/ui.py
@@ -235,6 +235,34 @@ def _(basic_ui_elements, documentation):
return
[email protected](hide_code=True)
+def _(mo):
+ mo.md(r"""
+ `mo.ui.matrix` lets you edit 2D numeric data interactively.
+ """)
+ return
+
+
+def _(mo):
+ matrix = mo.ui.matrix(
+ [[1, 0, 0], [0, 1, 0], [0, 0, 1]],
+ min_value=-5,
+ max_value=5,
+ step=0.1,
+ precision=1,
+ label="$I$",
+ )
+ matrix
+ return (matrix,)
+
+
+def _(matrix):
+ matrix.value
+ return
+
+
@app.cell(hide_code=True)
def _(mo):
mo.md("""
@@ -382,6 +410,7 @@ def _(mo):
"date": mo.ui.date,
"dropdown": mo.ui.dropdown,
"file": mo.ui.file,
+ "matrix": mo.ui.matrix,
"multiselect": mo.ui.multiselect,
"number": mo.ui.number,
"radio": mo.ui.radio,
@@ -441,6 +470,15 @@ def _(mo):
return [mo.ui.file(kind="button"), mo.ui.file(kind="area")]
elif value == mo.ui.form:
return mo.ui.text_area(placeholder="...").form()
+ elif value == mo.ui.matrix:
+ return mo.ui.matrix(
+ [[1, 0, 0], [0, 1, 0], [0, 0, 1]],
+ min_value=-5,
+ max_value=5,
+ step=0.1,
+ precision=1,
+ label="$I$",
+ )
elif value == mo.ui.multiselect:
return mo.ui.multiselect(["a", "b", "c"])
elif value == mo.ui.number:
diff --git a/mkdocs.yml b/mkdocs.yml
index 749d8fd895..d9256bd360 100644
--- a/mkdocs.yml
+++ b/mkdocs.yml
@@ -229,6 +229,8 @@ nav:
- File: api/inputs/file.md
- File Browser: api/inputs/file_browser.md
- Form: api/inputs/form.md
+ - Matrix: api/inputs/matrix.md
+ - Vector: api/inputs/vector.md
- Microphone: api/inputs/microphone.md
- Multiselect: api/inputs/multiselect.md
- Navigation Menu: api/inputs/nav_menu.md
diff --git a/tests/_plugins/ui/_impl/test_matrix.py b/tests/_plugins/ui/_impl/test_matrix.py
new file mode 100644
index 0000000000..530a4e8f39
--- /dev/null
+++ b/tests/_plugins/ui/_impl/test_matrix.py
@@ -0,0 +1,253 @@
+from __future__ import annotations
+
+import pytest
+
+from marimo._plugins import ui
+
+
+def test_matrix_basic():
+ m = ui.matrix([[1, 2], [3, 4]])
+ assert m.value == [[1.0, 2.0], [3.0, 4.0]]
+
+
+def test_matrix_debounce():
+ m = ui.matrix([[1, 2], [3, 4]], debounce=True)
+ assert m.value == [[1.0, 2.0], [3.0, 4.0]]
+
+
+def test_matrix_single_cell():
+ m = ui.matrix([[5]])
+ assert m.value == [[5.0]]
+
+
+def test_matrix_with_bounds():
+ m = ui.matrix(
+ [[0, 0], [0, 0]],
+ min_value=-10,
+ max_value=10,
+ step=0.5,
+ precision=2,
+ )
+ assert m.value == [[0.0, 0.0], [0.0, 0.0]]
+
+
+def test_matrix_with_per_element_bounds():
+ m = ui.matrix(
+ [[1, 2], [3, 4]],
+ min_value=[[0, 1], [2, 3]],
+ max_value=[[5, 6], [7, 8]],
+ )
+ assert m.value == [[1.0, 2.0], [3.0, 4.0]]
+
+
+def test_matrix_with_labels():
+ m = ui.matrix(
+ [[1, 2], [3, 4]],
+ row_labels=["r1", "r2"],
+ column_labels=["c1", "c2"],
+ )
+ assert m.value == [[1.0, 2.0], [3.0, 4.0]]
+
+
+def test_matrix_symmetric():
+ m = ui.matrix([[1, 2], [2, 1]], symmetric=True)
+ assert m.value == [[1.0, 2.0], [2.0, 1.0]]
+
+
+def test_matrix_convert_value():
+ m = ui.matrix([[1, 2], [3, 4]])
+ result = m._convert_value([[5, 6], [7, 8]])
+ assert result == [[5, 6], [7, 8]]
+
+
+def test_matrix_update():
+ m = ui.matrix([[1, 2], [3, 4]])
+ m._update([[10, 20], [30, 40]])
+ assert m.value == [[10, 20], [30, 40]]
+
+
+def test_matrix_disabled_scalar():
+ m = ui.matrix([[1, 2], [3, 4]], disabled=True)
+ assert m.value == [[1.0, 2.0], [3.0, 4.0]]
+
+
+def test_matrix_disabled_per_element():
+ m = ui.matrix(
+ [[1, 2], [3, 4]],
+ disabled=[[True, False], [False, True]],
+ )
+ assert m.value == [[1.0, 2.0], [3.0, 4.0]]
+
+
+# --- Validation error tests ---
+
+
+def test_matrix_empty_raises():
+ with pytest.raises(ValueError, match="non-empty"):
+ ui.matrix([])
+
+
+def test_matrix_non_list_raises():
+ with pytest.raises(ValueError, match="list of lists"):
+ ui.matrix("not a matrix")
+
+
+def test_matrix_inconsistent_rows_raises():
+ with pytest.raises(ValueError, match="columns but expected"):
+ ui.matrix([[1, 2], [3]])
+
+
+def test_matrix_min_ge_max_raises():
+ with pytest.raises(ValueError, match="less than"):
+ ui.matrix([[5]], min_value=10, max_value=5)
+
+
+def test_matrix_min_eq_max_raises():
+ with pytest.raises(ValueError, match="less than"):
+ ui.matrix([[5]], min_value=5, max_value=5)
+
+
+def test_matrix_value_below_min_raises():
+ with pytest.raises(ValueError, match="less than min_value"):
+ ui.matrix([[0]], min_value=1)
+
+
+def test_matrix_value_above_max_raises():
+ with pytest.raises(ValueError, match="greater than max_value"):
+ ui.matrix([[10]], max_value=5)
+
+
+def test_matrix_row_labels_mismatch_raises():
+ with pytest.raises(ValueError, match="row_labels"):
+ ui.matrix([[1, 2], [3, 4]], row_labels=["a"])
+
+
+def test_matrix_column_labels_mismatch_raises():
+ with pytest.raises(ValueError, match="column_labels"):
+ ui.matrix([[1, 2], [3, 4]], column_labels=["a", "b", "c"])
+
+
+def test_matrix_symmetric_non_square_raises():
+ with pytest.raises(ValueError, match="square"):
+ ui.matrix([[1, 2, 3], [4, 5, 6]], symmetric=True)
+
+
+def test_matrix_bounds_shape_mismatch_raises():
+ with pytest.raises(ValueError, match="rows"):
+ ui.matrix([[1, 2]], min_value=[[0, 0], [0, 0]])
+
+
+def test_matrix_negative_precision_raises():
+ with pytest.raises(ValueError, match="precision"):
+ ui.matrix([[1]], precision=-1)
+
+
+def test_matrix_scientific():
+ m = ui.matrix([[0.001, 1000]], scientific=True, precision=2)
+ assert m.value == [[0.001, 1000.0]]
+
+
+def test_matrix_numpy_array_like():
+ """Test that array-like objects with .tolist() are accepted."""
+
+ class FakeArray:
+ def tolist(self):
+ return [[1.0, 2.0], [3.0, 4.0]]
+
+ m = ui.matrix(FakeArray())
+ assert m.value == [[1.0, 2.0], [3.0, 4.0]]
+
+
+def test_matrix_empty_row_raises():
+ with pytest.raises(ValueError, match="non-empty"):
+ ui.matrix([[]])
+
+
+def test_matrix_step_zero_raises():
+ with pytest.raises(ValueError, match="step.*positive"):
+ ui.matrix([[1]], step=0)
+
+
+def test_matrix_step_negative_raises():
+ with pytest.raises(ValueError, match="step.*positive"):
+ ui.matrix([[1]], step=-0.5)
+
+
+def test_matrix_step_per_element_zero_raises():
+ with pytest.raises(ValueError, match="step.*positive"):
+ ui.matrix([[1, 2]], step=[[1, 0]])
+
+
+def test_matrix_3d_value_raises():
+ """Test that 3D input produces a clear error, not a confusing TypeError."""
+
+ class Fake3D:
+ def tolist(self):
+ return [[[1, 2], [3, 4]], [[5, 6], [7, 8]]]
+
+ with pytest.raises(ValueError, match="2D"):
+ ui.matrix(Fake3D())
+
+
+def test_matrix_3d_param_raises():
+ """Test that 3D input for a broadcast param raises clearly."""
+
+ class Fake3D:
+ def tolist(self):
+ return [[[1, 2], [3, 4]], [[5, 6], [7, 8]]]
+
+ with pytest.raises(ValueError, match="2D"):
+ ui.matrix([[1, 2], [3, 4]], min_value=Fake3D())
+
+
+def test_matrix_symmetric_asymmetric_data_raises():
+ with pytest.raises(ValueError, match="not symmetric"):
+ ui.matrix([[1, 2], [999, 1]], symmetric=True)
+
+
+def test_matrix_symmetric_valid():
+ m = ui.matrix([[1, 0.5], [0.5, 1]], symmetric=True)
+ assert m.value == [[1.0, 0.5], [0.5, 1.0]]
+
+
+def test_matrix_precision_default_integers():
+ """Integer data with default step=1 → precision 0."""
+ m = ui.matrix([[1, 2], [3, 4]])
+ assert m._component_args["precision"] == 0
+
+
+def test_matrix_precision_default_float_step():
+ """Float step should drive inferred precision."""
+ m = ui.matrix([[0, 0]], step=0.25)
+ assert m._component_args["precision"] == 2
+
+
+def test_matrix_precision_default_float_data():
+ """Float data values should drive inferred precision."""
+ m = ui.matrix([[1.5, 2.33]])
+ assert m._component_args["precision"] == 2
+
+
+def test_matrix_precision_explicit():
+ """Explicit precision should override auto-inference."""
+ m = ui.matrix([[1, 2]], precision=5)
+ assert m._component_args["precision"] == 5
+
+
+def test_matrix_precision_scientific_small():
+ """Scientific notation: 1e-8 needs 0 mantissa places, not 8."""
+ m = ui.matrix([[1e-8]], scientific=True)
+ assert m._component_args["precision"] == 0
+
+
+def test_matrix_precision_scientific_mixed():
+ """Scientific notation: 0.00153 → 1.53e-3 → 2 mantissa places."""
+ m = ui.matrix([[0.00153, 1e-8]], scientific=True)
+ assert m._component_args["precision"] == 2
+
+
+def test_matrix_precision_scientific_step():
+ """Scientific notation: step mantissa drives precision."""
+ m = ui.matrix([[0]], step=2.5e-3, scientific=True)
+ # 2.5e-3 → mantissa 2.5 → 1 decimal place
+ assert m._component_args["precision"] == 1
diff --git a/tests/_plugins/ui/_impl/test_vector.py b/tests/_plugins/ui/_impl/test_vector.py
new file mode 100644
index 0000000000..a435c75014
--- /dev/null
+++ b/tests/_plugins/ui/_impl/test_vector.py
@@ -0,0 +1,240 @@
+from __future__ import annotations
+
+import pytest
+
+from marimo._plugins import ui
+
+
+def test_vector_basic_column():
+ v = ui.vector([1, 2, 3])
+ assert v.value == [1, 2, 3]
+
+
+def test_vector_transposed_row():
+ v = ui.vector([1, 2, 3], transpose=True)
+ assert v.value == [1, 2, 3]
+
+
+def test_vector_single_element():
+ v = ui.vector([5])
+ assert v.value == [5]
+
+
+def test_vector_with_scalar_bounds():
+ v = ui.vector([0, 0, 0], min_value=-10, max_value=10, step=0.5)
+ assert v.value == [0, 0, 0]
+
+
+def test_vector_with_per_element_bounds():
+ v = ui.vector([1, 2, 3], min_value=[0, 1, 2], max_value=[5, 6, 7])
+ assert v.value == [1, 2, 3]
+
+
+def test_vector_with_per_element_step():
+ v = ui.vector([0, 0], step=[0.1, 0.5])
+ assert v.value == [0, 0]
+
+
+def test_vector_with_per_element_disabled():
+ v = ui.vector([1, 2, 3], disabled=[True, False, True])
+ assert v.value == [1, 2, 3]
+
+
+def test_vector_scalar_disabled():
+ v = ui.vector([1, 2], disabled=True)
+ assert v.value == [1, 2]
+
+
+def test_vector_entry_labels_column():
+ """entry_labels should map to row_labels for a column vector."""
+ v = ui.vector([1, 2, 3], entry_labels=["x", "y", "z"])
+ assert v._component_args["row-labels"] == ["x", "y", "z"]
+ assert v._component_args["column-labels"] is None
+
+
+def test_vector_entry_labels_transposed():
+ """entry_labels should map to column_labels for a row vector."""
+ v = ui.vector([1, 2, 3], transpose=True, entry_labels=["a", "b", "c"])
+ assert v._component_args["column-labels"] == ["a", "b", "c"]
+ assert v._component_args["row-labels"] is None
+
+
+def test_vector_convert_value():
+ v = ui.vector([1, 2, 3])
+ # Column vector: 2D is [[1], [2], [3]]
+ result = v._convert_value([[10], [20], [30]])
+ assert result == [10, 20, 30]
+
+
+def test_vector_convert_value_transposed():
+ v = ui.vector([1, 2, 3], transpose=True)
+ # Row vector: 2D is [[1, 2, 3]]
+ result = v._convert_value([[10, 20, 30]])
+ assert result == [10, 20, 30]
+
+
+def test_vector_update():
+ v = ui.vector([1, 2, 3])
+ v._update([[10], [20], [30]])
+ assert v.value == [10, 20, 30]
+
+
+def test_vector_update_transposed():
+ v = ui.vector([1, 2], transpose=True)
+ v._update([[10, 20]])
+ assert v.value == [10, 20]
+
+
+def test_vector_scientific():
+ v = ui.vector([0.001, 1000], scientific=True, precision=2)
+ assert v.value == [0.001, 1000]
+
+
+def test_vector_debounce():
+ v = ui.vector([1, 2], debounce=True)
+ assert v._component_args["debounce"] is True
+
+
+def test_vector_precision_explicit():
+ v = ui.vector([1.0], precision=5)
+ assert v._component_args["precision"] == 5
+
+
+def test_vector_precision_default_integers():
+ """Integer data with default step=1 → precision 0."""
+ v = ui.vector([1, 2, 3])
+ assert v._component_args["precision"] == 0
+
+
+def test_vector_precision_default_float_step():
+ """Float step should drive inferred precision."""
+ v = ui.vector([0, 0], step=0.1)
+ assert v._component_args["precision"] == 1
+
+
+def test_vector_precision_default_float_data():
+ """Float data values should drive inferred precision."""
+ v = ui.vector([1.5, 2.333])
+ assert v._component_args["precision"] == 3
+
+
+def test_vector_precision_scientific():
+ """Scientific notation: 1e-8 needs 0 mantissa places, not 8."""
+ v = ui.vector([1e-8, 0.00153], scientific=True)
+ assert v._component_args["precision"] == 2
+
+
+def test_vector_label():
+ v = ui.vector([1, 2], label="test label")
+ assert v.value == [1, 2]
+
+
+def test_vector_numpy_array():
+ """Test that 1D array-like objects with .tolist() are accepted."""
+
+ class FakeArray1D:
+ def tolist(self):
+ return [1.0, 2.0, 3.0]
+
+ v = ui.vector(FakeArray1D())
+ assert v.value == [1.0, 2.0, 3.0]
+
+
+def test_vector_numpy_bounds():
+ """Test that 1D array-like bounds are accepted."""
+
+ class FakeArray1D:
+ def tolist(self):
+ return [0.0, 0.0]
+
+ class FakeMins:
+ def tolist(self):
+ return [-5.0, -10.0]
+
+ class FakeMaxs:
+ def tolist(self):
+ return [5.0, 10.0]
+
+ v = ui.vector(FakeArray1D(), min_value=FakeMins(), max_value=FakeMaxs())
+ assert v.value == [0.0, 0.0]
+
+
+# --- Validation error tests ---
+
+
+def test_vector_empty_raises():
+ with pytest.raises(ValueError, match="non-empty"):
+ ui.vector([])
+
+
+def test_vector_non_list_raises():
+ with pytest.raises(ValueError, match="list or 1D"):
+ ui.vector("not a vector")
+
+
+def test_vector_nested_raises():
+ with pytest.raises(ValueError, match="1D"):
+ ui.vector([[1, 2], [3, 4]])
+
+
+def test_vector_min_ge_max_raises():
+ with pytest.raises(ValueError, match="less than"):
+ ui.vector([5], min_value=10, max_value=5)
+
+
+def test_vector_value_below_min_raises():
+ with pytest.raises(ValueError, match="less than min_value"):
+ ui.vector([0], min_value=1)
+
+
+def test_vector_value_above_max_raises():
+ with pytest.raises(ValueError, match="greater than max_value"):
+ ui.vector([10], max_value=5)
+
+
+def test_vector_step_zero_raises():
+ with pytest.raises(ValueError, match="step.*positive"):
+ ui.vector([1], step=0)
+
+
+def test_vector_step_negative_raises():
+ with pytest.raises(ValueError, match="step.*positive"):
+ ui.vector([1], step=-0.5)
+
+
+def test_vector_entry_labels_mismatch_raises():
+ with pytest.raises(ValueError, match="row_labels"):
+ ui.vector([1, 2, 3], entry_labels=["a"])
+
+
+def test_vector_entry_labels_transposed_mismatch_raises():
+ with pytest.raises(ValueError, match="column_labels"):
+ ui.vector([1, 2, 3], transpose=True, entry_labels=["a"])
+
+
+def test_vector_bounds_length_mismatch_raises():
+ with pytest.raises(ValueError, match="rows"):
+ ui.vector([1, 2], min_value=[0, 0, 0])
+
+
+def test_vector_negative_precision_raises():
+ with pytest.raises(ValueError, match="precision"):
+ ui.vector([1], precision=-1)
+
+
+def test_vector_2d_param_raises():
+ """1D params that are actually 2D should be rejected."""
+ with pytest.raises(ValueError, match="1D"):
+ ui.vector([1, 2], step=[[0.1, 0.2], [0.3, 0.4]])
+
+
+def test_vector_symmetric_not_exposed():
+ """vector should always set symmetric to False."""
+ v = ui.vector([1, 2])
+ assert v._component_args["symmetric"] is False
+
+
+def test_vector_uses_matrix_plugin():
+ """vector should use the marimo-matrix frontend component."""
+ v = ui.vector([1, 2])
+ assert v._name == "marimo-matrix"
diff --git a/tests/snapshots/api.txt b/tests/snapshots/api.txt
index 87a01015ae..78ac712cc2 100644
--- a/tests/snapshots/api.txt
+++ b/tests/snapshots/api.txt
@@ -104,6 +104,7 @@ ui
file
file_browser
form
+ matrix
microphone
multiselect
number
@@ -119,6 +120,7 @@ ui
tabs
text
text_area
+ vector
video
vstack
watch