{"record":{"id":"f375ab69beca7727","repo":"jax-ml/jax","slug":"jnp-linalg-cond-for-p-array-must-be-square-g","errorCode":null,"errorMessage":"jnp.linalg.cond: for {p=}, array must be square; got {arr.shape=}","messagePattern":"jnp\\.linalg\\.cond: for (.+?), array must be square; got (.+?)","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"jax/_src/numpy/linalg.py","lineNumber":2302,"sourceCode":"    >>> x = jnp.array([[1, 2],\n    ...                [0, 0]])\n    >>> jnp.linalg.cond(x)\n    Array(inf, dtype=float32)\n  \"\"\"\n  arr = ensure_arraylike(\"cond\", x)\n  if arr.ndim < 2:\n    raise ValueError(f\"jnp.linalg.cond: input array must be at least 2D; got {arr.shape=}\")\n  if arr.shape[-1] == 0 or arr.shape[-2] == 0:\n    raise ValueError(f\"jnp.linalg.cond: input array must not be empty; got {arr.shape=}\")\n  if p is None or p == 2:\n    s = svdvals(x)\n    return s[..., 0] / s[..., -1]\n  elif p == -2:\n    s = svdvals(x)\n    r = s[..., -1] / s[..., 0]\n  else:\n    if arr.shape[-2] != arr.shape[-1]:\n      raise ValueError(f\"jnp.linalg.cond: for {p=}, array must be square; got {arr.shape=}\")\n    r = norm(x, ord=p, axis=(-2, -1)) * norm(inv(x), ord=p, axis=(-2, -1))\n  # Convert NaNs to infs where original array has no NaNs.\n  return jnp.where(ufuncs.isnan(r) & ~ufuncs.isnan(x).any(axis=(-2, -1)), np.inf, r)\n\n\n@export\ndef trace(x: ArrayLike, /, *,\n          offset: int = 0, dtype: DTypeLike | None = None) -> Array:\n  \"\"\"Compute the trace of a matrix.\n\n  JAX implementation of :func:`numpy.linalg.trace`.\n\n  Args:\n    x: array of shape ``(..., M, N)`` and whose innermost two\n      dimensions form MxN matrices for which to take the trace.\n    offset: positive or negative offset from the main diagonal\n      (default: 0).\n    dtype: data type of the returned array (default: ``None``). If ``None``,","sourceCodeStart":2284,"sourceCodeEnd":2320,"githubUrl":"https://github.com/jax-ml/jax/blob/1e1c6a8fc06dfcd1247076ec5cae4640cea5d7bb/jax/_src/numpy/linalg.py#L2284-L2320","documentation":"Condition numbers for p norms other than 2/-2 (e.g. p=1 or p=jnp.inf) are computed as norm(x) * norm(inv(x)), which requires x to be square (invertible in the first place). jnp.linalg.cond therefore rejects non-square matrices when such a p is requested.","triggerScenarios":"jnp.linalg.cond(x, ord=1) or ord=jnp.inf with x of shape (m, n), m != n; rectangular inputs from least-squares problems.","commonSituations":"Analyzing conditioning of a design matrix in a regression pipeline with ord=1/inf; defaulting p to 1 in code reused from square-matrix contexts.","solutions":["Use p=None (default, 2-norm via SVD), which supports rectangular matrices (ratio of extreme singular values).","Square the matrix first if a square normal-equations view is acceptable (A^T A).","Pass the original square operator if a rectangular one was produced by mistake."],"exampleFix":"// before\nc = jnp.linalg.cond(A, ord=1)  # A: (m, n), m != n\n// after\nc = jnp.linalg.cond(A)  # 2-norm condition via SVD, works for rectangular","handlingStrategy":"validation","validationCode":"if p not in (None, 2, -2) and a.shape[-2] != a.shape[-1]:\n    p = None  # fall back to SVD-based 2-norm cond\nc = jnp.linalg.cond(a, p)","typeGuard":"def cond_p_needs_square(p) -> bool:\n    return p is not None and p not in (2, -2)","tryCatchPattern":null,"preventionTips":["Use default p=None for rectangular matrices","Remember only p=2/-2 work without square matrices"],"tags":["jax","numpy","linalg","condition-number","shape-validation"],"backgroundTag":"invalid-shape-argument","analyzedSha":"1e1c6a8fc06dfcd1247076ec5cae4640cea5d7bb","analyzedAt":"2026-08-27T09:53:25.647Z","schemaVersion":2},"datasetVersion":"2026-08-27T13:17:12.746Z"}