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: support vectors in ui.matrix (#8379)

Akshay Agrawal7bde0e61b63a
diff --git a/docs/_static/example-thumbs/vector.png b/docs/_static/example-thumbs/vector.png
deleted file mode 100644
index ad5197c56c..0000000000
Binary files a/docs/_static/example-thumbs/vector.png and /dev/null differ
diff --git a/docs/api/inputs/index.md b/docs/api/inputs/index.md
index 43c60cd1ce..4334103e40 100644
--- a/docs/api/inputs/index.md
+++ b/docs/api/inputs/index.md
@@ -21,8 +21,7 @@ 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.matrix`][marimo.ui.matrix] | Interactive matrix/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
index 148b82b451..61a1a1a5a6 100644
--- a/docs/api/inputs/matrix.md
+++ b/docs/api/inputs/matrix.md
@@ -24,4 +24,30 @@ def __():
///
+`mo.ui.matrix` also supports 1D (vector) input:
+
+/// marimo-embed
+
+```python
+def __():
+ vector = mo.ui.matrix(
+ [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.matrix
diff --git a/docs/api/inputs/vector.md b/docs/api/inputs/vector.md
deleted file mode 100644
index fce081a982..0000000000
--- a/docs/api/inputs/vector.md
+++ /dev/null
@@ -1,27 +0,0 @@
-# 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 3484d433f3..26d39a6cd0 100644
--- a/docs/examples/index.md
+++ b/docs/examples/index.md
@@ -301,12 +301,6 @@ guide](../guides/interactivity.md) for rules governing how UI elements work.
<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
index 21450c7bb8..59f68f6567 100644
--- a/examples/ui/matrix.py
+++ b/examples/ui/matrix.py
@@ -1,14 +1,15 @@
import marimo
-__generated_with = "0.19.7"
+__generated_with = "0.19.11"
app = marimo.App(width="medium")
@app.cell
def _():
import marimo as mo
+ import numpy as np
- return (mo,)
+ return mo, np
@app.cell
@@ -16,9 +17,10 @@ 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,
+ max_value=10,
+ step=0.001,
+ precision=3,
+ scientific=True,
label="$I$",
)
matrix
@@ -31,5 +33,15 @@ def _(matrix):
return
+def _(mo, np):
+ mo.hstack(
+ [mo.ui.matrix(np.ones(3)), mo.ui.matrix(np.ones((1, 3)))],
+ justify="start",
+ gap=2,
+ )
+ return
+
+
if __name__ == "__main__":
app.run()
diff --git a/examples/ui/vector.py b/examples/ui/vector.py
deleted file mode 100644
index 0831320a9d..0000000000
--- a/examples/ui/vector.py
+++ /dev/null
@@ -1,41 +0,0 @@
-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
index 81608a2666..140c42f0d6 100644
--- a/frontend/src/plugins/impl/MatrixPlugin.tsx
+++ b/frontend/src/plugins/impl/MatrixPlugin.tsx
@@ -241,7 +241,7 @@ const MatrixComponent = ({
<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",
+ "relative text-center 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",
diff --git a/marimo/_plugins/ui/__init__.py b/marimo/_plugins/ui/__init__.py
index a350597843..d190d196ad 100644
--- a/marimo/_plugins/ui/__init__.py
+++ b/marimo/_plugins/ui/__init__.py
@@ -42,7 +42,6 @@ __all__ = [
"tabs",
"text_area",
"text",
- "vector",
]
from marimo._plugins.ui._impl.altair_chart import altair_chart
@@ -88,4 +87,3 @@ 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
index 21617b4855..3f6806016c 100644
--- a/marimo/_plugins/ui/_impl/matrix.py
+++ b/marimo/_plugins/ui/_impl/matrix.py
@@ -54,13 +54,68 @@ def _broadcast(
return param
-def _to_nested_list(
- value: list[list[Numeric]] | ArrayLike,
-) -> list[list[Numeric]]:
- """Parse and validate initial matrix data into a nested list.
+def _to_flat_list(
+ value: list[Numeric] | ArrayLike,
+) -> list[Numeric]:
+ """Validate and convert input to a flat list of numbers.
- Accepts a nested list of numbers or a numpy array-like with `.tolist()`.
- Rejects empty, non-2D, or ragged inputs.
+ 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 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,
+) -> Any:
+ """Convert a 1D list param to a column-vector 2D layout.
+
+ Scalars pass through unchanged (they'll be broadcast by `_broadcast`).
+ A 1D list `[a, b, c]` becomes `[[a], [b], [c]]`.
+ """
+ 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__}"
+ )
+
+ return [[v] for v in param]
+
+
+def _parse_value(
+ value: list[list[Numeric]] | list[Numeric] | ArrayLike,
+) -> tuple[list[list[Numeric]], bool]:
+ """Parse and validate initial matrix data.
+
+ Returns `(data_2d, is_vector)` where *is_vector* is True when the
+ input was a flat 1D list.
"""
if hasattr(value, "tolist"):
value = value.tolist()
@@ -74,11 +129,19 @@ def _to_nested_list(
raise ValueError("`value` must be non-empty")
first = value[0]
- if not isinstance(first, (list, tuple)) or not first:
+
+ # 1D path
+ if not isinstance(first, (list, tuple)):
+ flat = _to_flat_list(value)
+ return flat, True # type: ignore[return-value]
+
+ # 2D path
+ if 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))
+ data_2d = _broadcast("value", value, len(value), len(first))
+ return data_2d, False
def _decimal_places(x: Numeric) -> int:
@@ -99,11 +162,11 @@ def _decimal_places(x: Numeric) -> int:
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.
+ 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
+ # Strip trailing zeros: 1234000 -> 1.234e6 -> 3 places
if x == 0:
return 0
s = str(abs(x)).rstrip("0")
@@ -137,7 +200,7 @@ def _infer_precision(
for row in step_val:
for v in row:
best = max(best, counter(v))
- return best
+ return min(best, 8)
def _validate_and_build_args(
@@ -234,17 +297,24 @@ def _validate_and_build_args(
@mddoc
-class matrix(UIElement[list[list[Numeric]], list[list[Numeric]]]):
- """An interactive matrix editor.
+class matrix(
+ UIElement[list[list[Numeric]], list[list[Numeric]] | list[Numeric]]
+):
+ """An interactive matrix/vector 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.
+ 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. These
+ configuration values may be any array-like object, including as lists,
+ NumPy arrays, or torch Tensors.
+
+ Supports both 2D (matrix) and 1D (vector) inputs. When a flat list is
+ passed, the element displays as a column vector and `.value` returns a flat
+ list.
Examples:
- Basic usage:
+ Basic 2D matrix:
```python
mat = mo.ui.matrix([[1, 0], [0, 1]])
@@ -254,7 +324,21 @@ class matrix(UIElement[list[list[Numeric]], list[list[Numeric]]]):
Access the value in another cell with
```python
- mat.value
+ mat.value # [[1, 0], [0, 1]]
+ ```
+
+ Column vector (1D input):
+
+ ```python
+ v = mo.ui.matrix([1, 2, 3])
+ v.value # [1, 2, 3]
+ ```
+
+ Row vecto
+
+ ```python
+ v = mo.ui.matrix([[1, 2, 3]])
+ v.value # [[1, 2, 3]]
```
You can specify bounds and a step size as well:
@@ -293,30 +377,34 @@ class matrix(UIElement[list[list[Numeric]], list[list[Numeric]]]):
```
Attributes:
- value (list[list[Numeric]]): The current 2D matrix as a nested list.
+ value (list[list[Numeric]] | list[Numeric]): The current matrix
+ as a nested list, or a flat list when created with 1D input.
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):
+ value (list[list[Numeric]] | list[Numeric] | ArrayLike): Initial
+ data. A nested list or 2D array creates a matrix; a flat list
+ or 1D array creates a column vector. Rows and columns are
+ inferred from the shape.
+ min_value (Numeric | list[list[Numeric]] | 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):
+ list or numpy array sets per-element bounds. For 1D input,
+ accepts a flat list. None means unbounded. Defaults to None.
+ max_value (Numeric | list[list[Numeric]] | 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.
+ list or numpy array sets per-element bounds. For 1D input,
+ accepts a flat list. None means unbounded. Defaults to None.
+ step (Numeric | list[list[Numeric]] | list[Numeric] | ArrayLike, optional):
+ Drag increment. A scalar is broadcast to all cells; a list
+ or numpy array sets per-element step sizes. For 1D input,
+ accepts a flat list. Defaults to 1.0.
+ disabled (bool | list[list[bool]] | list[bool] | ArrayLike, optional):
+ Whether cells are disabled. A scalar bool is broadcast to all
+ cells; a list or numpy bool array sets a per-element mask.
+ For 1D input, accepts a flat list. Defaults to False.
symmetric (bool, optional): If True, editing cell `[i][j]` also
- updates cell `[j][i]`. Requires a square matrix. Defaults to False.
+ 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
@@ -338,12 +426,18 @@ class matrix(UIElement[list[list[Numeric]], list[list[Numeric]]]):
def __init__(
self,
- value: list[list[Numeric]] | ArrayLike,
+ value: list[list[Numeric]] | 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,
+ min_value: (
+ Numeric | list[list[Numeric]] | list[Numeric] | ArrayLike | None
+ ) = None,
+ max_value: (
+ Numeric | list[list[Numeric]] | list[Numeric] | ArrayLike | None
+ ) = None,
+ step: (
+ Numeric | list[list[Numeric]] | list[Numeric] | ArrayLike
+ ) = 1.0,
+ disabled: bool | list[list[bool]] | list[bool] | ArrayLike = False,
symmetric: bool = False,
scientific: bool = False,
precision: int | None = None,
@@ -352,24 +446,60 @@ class matrix(UIElement[list[list[Numeric]], list[list[Numeric]]]):
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)
+ parsed, is_vector = _parse_value(value)
+
+ if is_vector:
+ # --- 1D (vector) path: always a column vector ---
+ flat: list[Numeric] = parsed # type: ignore[assignment]
+
+ if symmetric:
+ raise ValueError(
+ "`symmetric` is not supported for 1D (vector) input"
+ )
+
+ data: list[list[Numeric]] = [[v] for v in flat]
+ rows = len(data)
+ cols = 1
+
+ # Convert 1D params -> 2D column layout
+ min_2d = _1d_to_2d("min_value", min_value)
+ max_2d = _1d_to_2d("max_value", max_value)
+ step_2d = _1d_to_2d("step", step)
+ disabled_2d = _1d_to_2d("disabled", disabled)
+
+ 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)
+
+ else:
+ # --- 2D (matrix) path ---
+ data = parsed # type: ignore[assignment]
+ rows = len(data)
+ cols = len(data[0])
+
+ 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)
+
+ self._is_vector = is_vector
args = _validate_and_build_args(
data,
@@ -395,5 +525,7 @@ class matrix(UIElement[list[list[Numeric]], list[list[Numeric]]]):
def _convert_value(
self, value: list[list[Numeric]]
- ) -> list[list[Numeric]]:
+ ) -> list[list[Numeric]] | list[Numeric]:
+ if self._is_vector:
+ return [cell for row in value for cell in row]
return value
diff --git a/marimo/_plugins/ui/_impl/vector.py b/marimo/_plugins/ui/_impl/vector.py
deleted file mode 100644
index 068b16dde7..0000000000
--- a/marimo/_plugins/ui/_impl/vector.py
+++ /dev/null
@@ -1,255 +0,0 @@
-# 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
index 821b1fe613..5b6c5ff3b8 100644
--- a/marimo/_smoke_tests/matrix.py
+++ b/marimo/_smoke_tests/matrix.py
@@ -371,5 +371,37 @@ def _(mo, np):
return
[email protected](hide_code=True)
+def _(mo):
+ mo.md(r"""
+ ## Column vector
+ """)
+ return
+
+
+def _(mo, vecnp):
+ vec = mo.ui.matrix([1, 2, 3]);vecnp
+ return (vec,)
+
+
+def _(vec):
+ vec.value
+ return
+
+
+def _(mo, np):
+ vecnp = mo.ui.matrix(np.ones(3)); vecnp
+ return (vecnp,)
+
+
+def _(vecnp):
+ vecnp.value
+ return
+
+
if __name__ == "__main__":
app.run()
diff --git a/marimo/_smoke_tests/vector.py b/marimo/_smoke_tests/vector.py
index 6a022f5d6c..8f76ee4879 100644
--- a/marimo/_smoke_tests/vector.py
+++ b/marimo/_smoke_tests/vector.py
@@ -16,14 +16,14 @@ def _():
@app.cell(hide_code=True)
def _(mo):
mo.md("""
- ## Basic column vector
+ ## Basic column vector (1D matrix)
""")
return
@app.cell
def _(mo):
- col = mo.ui.vector([1, 2, 3], precision=2, label="Column vector")
+ col = mo.ui.matrix([1, 2, 3], precision=2, label="Column vector")
col
return (col,)
@@ -34,27 +34,6 @@ def _(col):
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
-
-
@app.cell(hide_code=True)
def _(mo):
mo.md("""
@@ -65,7 +44,7 @@ def _(mo):
@app.cell
def _(mo):
- bounded = mo.ui.vector(
+ bounded = mo.ui.matrix(
[0, 0, 0, 0],
min_value=-5,
max_value=5,
@@ -86,16 +65,16 @@ def _(bounded):
@app.cell(hide_code=True)
def _(mo):
mo.md("""
- ## With entry labels
+ ## With row labels
""")
return
@app.cell
def _(mo):
- labeled = mo.ui.vector(
+ labeled = mo.ui.matrix(
[1.0, 0.5, 0.0],
- entry_labels=["x", "y", "z"],
+ row_labels=["x", "y", "z"],
step=0.1,
precision=1,
label="$v$",
@@ -122,7 +101,7 @@ def _(mo):
def _(mo):
import numpy as np
- np_vec = mo.ui.vector(
+ np_vec = mo.ui.matrix(
np.zeros(5),
step=0.1,
precision=1,
@@ -148,7 +127,7 @@ def _(mo):
@app.cell
def _(mo):
- sci = mo.ui.vector(
+ sci = mo.ui.matrix(
[0.00153, 1234567, 1e-8, -0.042],
scientific=True,
precision=2,
@@ -175,7 +154,7 @@ def _(mo):
@app.cell
def _(mo):
- db = mo.ui.vector(
+ db = mo.ui.matrix(
[1, 2, 3],
precision=2,
debounce=True,
diff --git a/mkdocs.yml b/mkdocs.yml
index d9256bd360..56cf52ce17 100644
--- a/mkdocs.yml
+++ b/mkdocs.yml
@@ -230,7 +230,6 @@ nav:
- 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
index 530a4e8f39..a6d8b01100 100644
--- a/tests/_plugins/ui/_impl/test_matrix.py
+++ b/tests/_plugins/ui/_impl/test_matrix.py
@@ -4,6 +4,10 @@ import pytest
from marimo._plugins import ui
+# =========================================================================
+# 2D matrix tests (original)
+# =========================================================================
+
def test_matrix_basic():
m = ui.matrix([[1, 2], [3, 4]])
@@ -79,7 +83,7 @@ def test_matrix_disabled_per_element():
assert m.value == [[1.0, 2.0], [3.0, 4.0]]
-# --- Validation error tests ---
+# --- 2D validation error tests ---
def test_matrix_empty_raises():
@@ -211,7 +215,7 @@ def test_matrix_symmetric_valid():
def test_matrix_precision_default_integers():
- """Integer data with default step=1 → precision 0."""
+ """Integer data with default step=1 -> precision 0."""
m = ui.matrix([[1, 2], [3, 4]])
assert m._component_args["precision"] == 0
@@ -241,7 +245,7 @@ def test_matrix_precision_scientific_small():
def test_matrix_precision_scientific_mixed():
- """Scientific notation: 0.00153 → 1.53e-3 → 2 mantissa places."""
+ """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
@@ -249,5 +253,201 @@ def test_matrix_precision_scientific_mixed():
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
+ # 2.5e-3 -> mantissa 2.5 -> 1 decimal place
assert m._component_args["precision"] == 1
+
+
+# =========================================================================
+# 1D (vector) tests
+# =========================================================================
+
+
+def test_matrix_1d_column():
+ """1D input creates a column vector; value is a flat list."""
+ m = ui.matrix([1, 2, 3])
+ assert m.value == [1, 2, 3]
+
+
+def test_matrix_1d_single_element():
+ m = ui.matrix([5])
+ assert m.value == [5]
+
+
+def test_matrix_1d_scalar_bounds():
+ m = ui.matrix([0, 0, 0], min_value=-10, max_value=10, step=0.5)
+ assert m.value == [0, 0, 0]
+
+
+def test_matrix_1d_per_element_bounds():
+ m = ui.matrix([1, 2, 3], min_value=[0, 1, 2], max_value=[5, 6, 7])
+ assert m.value == [1, 2, 3]
+
+
+def test_matrix_1d_per_element_step():
+ m = ui.matrix([0, 0], step=[0.1, 0.5])
+ assert m.value == [0, 0]
+
+
+def test_matrix_1d_per_element_disabled():
+ m = ui.matrix([1, 2, 3], disabled=[True, False, True])
+ assert m.value == [1, 2, 3]
+
+
+def test_matrix_1d_scalar_disabled():
+ m = ui.matrix([1, 2], disabled=True)
+ assert m.value == [1, 2]
+
+
+def test_matrix_1d_row_labels():
+ """For column vector, row_labels are set."""
+ m = ui.matrix([1, 2, 3], row_labels=["x", "y", "z"])
+ assert m._component_args["row-labels"] == ["x", "y", "z"]
+ assert m._component_args["column-labels"] is None
+
+
+def test_matrix_1d_convert_value():
+ """_convert_value flattens 2D back to 1D for column vector."""
+ m = ui.matrix([1, 2, 3])
+ result = m._convert_value([[10], [20], [30]])
+ assert result == [10, 20, 30]
+
+
+def test_matrix_1d_update():
+ m = ui.matrix([1, 2, 3])
+ m._update([[10], [20], [30]])
+ assert m.value == [10, 20, 30]
+
+
+def test_matrix_1d_scientific():
+ m = ui.matrix([0.001, 1000], scientific=True, precision=2)
+ assert m.value == [0.001, 1000]
+
+
+def test_matrix_1d_debounce():
+ m = ui.matrix([1, 2], debounce=True)
+ assert m._component_args["debounce"] is True
+
+
+def test_matrix_1d_precision_explicit():
+ m = ui.matrix([1.0], precision=5)
+ assert m._component_args["precision"] == 5
+
+
+def test_matrix_1d_precision_default_integers():
+ """Integer data with default step=1 -> precision 0."""
+ m = ui.matrix([1, 2, 3])
+ assert m._component_args["precision"] == 0
+
+
+def test_matrix_1d_precision_default_float_step():
+ """Float step should drive inferred precision."""
+ m = ui.matrix([0, 0], step=0.1)
+ assert m._component_args["precision"] == 1
+
+
+def test_matrix_1d_precision_default_float_data():
+ """Float data values should drive inferred precision."""
+ m = ui.matrix([1.5, 2.333])
+ assert m._component_args["precision"] == 3
+
+
+def test_matrix_1d_precision_scientific():
+ """Scientific notation: 1e-8 needs 0 mantissa places, not 8."""
+ m = ui.matrix([1e-8, 0.00153], scientific=True)
+ assert m._component_args["precision"] == 2
+
+
+def test_matrix_1d_label():
+ m = ui.matrix([1, 2], label="test label")
+ assert m.value == [1, 2]
+
+
+def test_matrix_1d_numpy_array():
+ """Test that 1D array-like objects with .tolist() are accepted."""
+
+ class FakeArray1D:
+ def tolist(self):
+ return [1.0, 2.0, 3.0]
+
+ m = ui.matrix(FakeArray1D())
+ assert m.value == [1.0, 2.0, 3.0]
+
+
+def test_matrix_1d_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]
+
+ m = ui.matrix(FakeArray1D(), min_value=FakeMins(), max_value=FakeMaxs())
+ assert m.value == [0.0, 0.0]
+
+
+# --- 1D validation error tests ---
+
+
+def test_matrix_1d_empty_raises():
+ with pytest.raises(ValueError, match="non-empty"):
+ ui.matrix([])
+
+
+def test_matrix_1d_min_ge_max_raises():
+ with pytest.raises(ValueError, match="less than"):
+ ui.matrix([5], min_value=10, max_value=5)
+
+
+def test_matrix_1d_value_below_min_raises():
+ with pytest.raises(ValueError, match="less than min_value"):
+ ui.matrix([0], min_value=1)
+
+
+def test_matrix_1d_value_above_max_raises():
+ with pytest.raises(ValueError, match="greater than max_value"):
+ ui.matrix([10], max_value=5)
+
+
+def test_matrix_1d_step_zero_raises():
+ with pytest.raises(ValueError, match="step.*positive"):
+ ui.matrix([1], step=0)
+
+
+def test_matrix_1d_step_negative_raises():
+ with pytest.raises(ValueError, match="step.*positive"):
+ ui.matrix([1], step=-0.5)
+
+
+def test_matrix_1d_bounds_length_mismatch_raises():
+ with pytest.raises(ValueError, match="rows"):
+ ui.matrix([1, 2], min_value=[0, 0, 0])
+
+
+def test_matrix_1d_negative_precision_raises():
+ with pytest.raises(ValueError, match="precision"):
+ ui.matrix([1], precision=-1)
+
+
+def test_matrix_1d_2d_param_raises():
+ """1D params that are actually 2D should be rejected."""
+ with pytest.raises(ValueError, match="1D"):
+ ui.matrix([1, 2], step=[[0.1, 0.2], [0.3, 0.4]])
+
+
+def test_matrix_1d_symmetric_raises():
+ """symmetric=True with 1D input should raise."""
+ with pytest.raises(ValueError, match="symmetric.*not supported.*1D"):
+ ui.matrix([1, 2], symmetric=True)
+
+
+def test_matrix_1d_uses_matrix_plugin():
+ """1D input should use the marimo-matrix frontend component."""
+ m = ui.matrix([1, 2])
+ assert m._name == "marimo-matrix"
diff --git a/tests/_plugins/ui/_impl/test_vector.py b/tests/_plugins/ui/_impl/test_vector.py
deleted file mode 100644
index a435c75014..0000000000
--- a/tests/_plugins/ui/_impl/test_vector.py
+++ /dev/null
@@ -1,240 +0,0 @@
-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 6e2d57d91a..c4f76e80e6 100644
--- a/tests/snapshots/api.txt
+++ b/tests/snapshots/api.txt
@@ -121,9 +121,8 @@ ui
tabs
text
text_area
- vector
video
vstack
watch
directory
- file
+ file
\ No newline at end of file