> ## Documentation Index
> Fetch the complete documentation index at: https://resources.latex-cloud-studio.com/llms.txt
> Use this file to discover all available pages before exploring further.

# LaTeX Matrix Tutorial - pmatrix, bmatrix, vmatrix, and More

> Learn how to write a matrix in LaTeX with pmatrix, bmatrix, vmatrix, smallmatrix, augmented matrices, and block matrices using copy-paste examples.

export const RenderedOutput = ({title = "Rendered output", ctaHref, ctaLabel = "Open LaTeX Cloud Studio", children}) => {
  const [isExpanded, setIsExpanded] = useState(false);
  const trackEditorCta = () => {
    const target = new URL(ctaHref, window.location.href);
    globalThis.posthog?.capture?.("docs_app_cta_clicked", {
      source_page: window.location.pathname,
      source_section: "rendered_output",
      cta_variant: "first_compiled_example",
      target_url: target.toString(),
      target_utm_source: target.searchParams.get("utm_source"),
      target_utm_medium: target.searchParams.get("utm_medium"),
      target_utm_campaign: target.searchParams.get("utm_campaign"),
      target_utm_content: target.searchParams.get("utm_content")
    }, {
      transport: "sendBeacon",
      send_instantly: true
    });
  };
  return <details className="rendered-output" onToggle={event => setIsExpanded(event.currentTarget.open)}>
      <summary className="rendered-output__summary">
        <span className="rendered-output__title">{title}</span>
        <span className="rendered-output__hint" aria-hidden="true">View compiled result</span>
      </summary>
      {isExpanded && <div className="rendered-output__content">
          {children}
          {ctaHref && <aside className="rendered-output__cta" aria-label="Continue in the LaTeX editor">
              <span>
                <strong>Ready to use this syntax?</strong>
                Continue in the browser editor when you want to adapt the example in a real project.
              </span>
              <a href={ctaHref} onClick={trackEditorCta}>{ctaLabel}<span aria-hidden="true"> →</span></a>
            </aside>}
        </div>}
    </details>;
};

export const LatexSource = ({filename, source}) => {
  const [copyStatus, setCopyStatus] = useState("Copy");
  const copySource = async () => {
    try {
      await navigator.clipboard.writeText(source);
      setCopyStatus("Copied");
    } catch {
      setCopyStatus("Select and copy");
    }
  };
  return <figure className="latex-source">
      <figcaption className="latex-source__header">
        <span className="latex-source__filename">{filename}</span>
        <button type="button" className="latex-source__copy" onClick={copySource} aria-live="polite">
          {copyStatus}
        </button>
      </figcaption>
      <pre className="latex-source__pre" aria-label={`LaTeX source: ${filename}`} tabIndex="0">
        <code className="language-latex">{source}</code>
      </pre>
    </figure>;
};

export const LatexPreview = ({src, alt, caption, width, height}) => {
  const minZoom = 1;
  const maxZoom = 3;
  const zoomStep = 0.5;
  const measureSvgContent = async (assetSrc, pageWidth, pageHeight) => {
    const cacheKey = "__latexCloudSvgContentBoxCache";
    const contentBoxCache = globalThis[cacheKey] ?? new Map();
    globalThis[cacheKey] = contentBoxCache;
    if (contentBoxCache.has(assetSrc)) return contentBoxCache.get(assetSrc);
    const measurement = (async () => {
      const assetUrl = new URL(assetSrc, window.location.href);
      if (assetUrl.origin !== window.location.origin) {
        throw new Error("Rendered output must use a same-origin SVG asset.");
      }
      const response = await fetch(assetUrl, {
        credentials: "same-origin"
      });
      if (!response.ok) throw new Error(`Rendered output request failed with ${response.status}.`);
      const source = await response.text();
      const documentNode = new DOMParser().parseFromString(source, "image/svg+xml");
      if (documentNode.querySelector("parsererror")) throw new Error("Rendered output is not valid SVG.");
      const sourceSvg = documentNode.documentElement;
      sourceSvg.querySelectorAll("script, foreignObject").forEach(node => node.remove());
      [sourceSvg, ...sourceSvg.querySelectorAll("*")].forEach(node => {
        [...node.attributes].forEach(attribute => {
          if ((/^on/i).test(attribute.name)) node.removeAttribute(attribute.name);
          if ((attribute.name === "href" || attribute.name === "xlink:href") && !attribute.value.startsWith("#")) {
            node.removeAttribute(attribute.name);
          }
        });
      });
      const measurementHost = document.createElement("div");
      measurementHost.className = "latex-preview__measurement-host";
      const measuredSvg = document.importNode(sourceSvg, true);
      measuredSvg.setAttribute("aria-hidden", "true");
      measurementHost.appendChild(measuredSvg);
      document.body.appendChild(measurementHost);
      try {
        const measuredElements = [...measuredSvg.children].filter(node => !["defs", "desc", "metadata", "style", "title"].includes(node.tagName.toLowerCase()));
        const elementBounds = measuredElements.map(node => node.getBBox()).filter(box => [box.x, box.y, box.width, box.height].every(Number.isFinite) && box.width > 0 && box.height > 0);
        if (elementBounds.length === 0) {
          throw new Error("Rendered output has no measurable visible content.");
        }
        const sortedBounds = [...elementBounds].sort((left, right) => left.y - right.y);
        const clusterGap = pageHeight * 0.045;
        const clusters = [];
        sortedBounds.forEach(box => {
          const current = clusters[clusters.length - 1];
          if (!current || box.y - current.bottom > clusterGap) {
            clusters.push({
              boxes: [box],
              bottom: box.y + box.height
            });
            return;
          }
          current.boxes.push(box);
          current.bottom = Math.max(current.bottom, box.y + box.height);
        });
        const contentClusters = clusters.filter(cluster => {
          const clusterBox = cluster.boxes.reduce((combined, box) => {
            const right = Math.max(combined.x + combined.width, box.x + box.width);
            const bottom = Math.max(combined.y + combined.height, box.y + box.height);
            const x = Math.min(combined.x, box.x);
            const y = Math.min(combined.y, box.y);
            return {
              x,
              y,
              width: right - x,
              height: bottom - y
            };
          });
          const centerY = clusterBox.y + clusterBox.height / 2;
          const isMarginFurniture = cluster.boxes.length <= 2 && clusterBox.width < pageWidth * 0.2 && clusterBox.height < pageHeight * 0.04 && (centerY < pageHeight * 0.08 || centerY > pageHeight * 0.8);
          return !isMarginFurniture;
        });
        const visibleBounds = (contentClusters.length > 0 ? contentClusters : clusters).flatMap(cluster => cluster.boxes);
        const bounds = visibleBounds.reduce((combined, box) => {
          const right = Math.max(combined.x + combined.width, box.x + box.width);
          const bottom = Math.max(combined.y + combined.height, box.y + box.height);
          const x = Math.min(combined.x, box.x);
          const y = Math.min(combined.y, box.y);
          return {
            x,
            y,
            width: right - x,
            height: bottom - y
          };
        });
        const clampValue = (value, minimum, maximum) => Math.min(maximum, Math.max(minimum, value));
        const padding = Math.max(8, Math.min(pageWidth, pageHeight) * 0.025);
        const x = clampValue(bounds.x - padding, 0, pageWidth);
        const y = clampValue(bounds.y - padding, 0, pageHeight);
        const right = clampValue(bounds.x + bounds.width + padding, 0, pageWidth);
        const bottom = clampValue(bounds.y + bounds.height + padding, 0, pageHeight);
        return {
          x,
          y,
          width: right - x,
          height: bottom - y
        };
      } finally {
        measurementHost.remove();
      }
    })();
    contentBoxCache.set(assetSrc, measurement);
    measurement.catch(() => contentBoxCache.delete(assetSrc));
    return measurement;
  };
  const renderPreviewAsset = ({contentBox: assetContentBox, loading}) => {
    if (!assetContentBox) {
      return <img className="latex-preview__asset" src={src} alt={alt} width={width} height={height} loading={loading} draggable="false" />;
    }
    return <svg className="latex-preview__asset" viewBox={`${assetContentBox.x} ${assetContentBox.y} ${assetContentBox.width} ${assetContentBox.height}`} preserveAspectRatio="xMidYMid meet" role="img" aria-label={alt}>
        <image href={src} x="0" y="0" width={width} height={height} />
      </svg>;
  };
  const [isOpen, setIsOpen] = useState(false);
  const [frameMode, setFrameMode] = useState("content");
  const [viewMode, setViewMode] = useState("fit");
  const [zoom, setZoom] = useState(minZoom);
  const [contentBox, setContentBox] = useState(null);
  const [measurementStatus, setMeasurementStatus] = useState("loading");
  const dialogRef = useRef(null);
  const closeButtonRef = useRef(null);
  const viewportRef = useRef(null);
  const previousFocusRef = useRef(null);
  const dragRef = useRef(null);
  useEffect(() => {
    let isCurrent = true;
    setMeasurementStatus("loading");
    measureSvgContent(src, width, height).then(box => {
      if (!isCurrent) return;
      setContentBox(box);
      setMeasurementStatus("ready");
    }).catch(() => {
      if (!isCurrent) return;
      setContentBox(null);
      setFrameMode("page");
      setMeasurementStatus("error");
    });
    return () => {
      isCurrent = false;
    };
  }, [height, src, width]);
  const closeViewer = useCallback(() => {
    setIsOpen(false);
  }, []);
  const openViewer = () => {
    previousFocusRef.current = document.activeElement;
    setFrameMode(contentBox ? "content" : "page");
    setViewMode("fit");
    setZoom(minZoom);
    setIsOpen(true);
  };
  const applyZoom = useCallback(nextZoom => {
    const boundedZoom = Math.min(maxZoom, Math.max(minZoom, nextZoom));
    setViewMode("custom");
    setZoom(boundedZoom);
  }, []);
  const zoomIn = useCallback(() => {
    applyZoom(viewMode === "fit" ? minZoom + zoomStep : zoom + zoomStep);
  }, [applyZoom, viewMode, zoom]);
  const zoomOut = useCallback(() => {
    applyZoom(viewMode === "fit" ? minZoom : zoom - zoomStep);
  }, [applyZoom, viewMode, zoom]);
  useEffect(() => {
    if (!isOpen) return undefined;
    const previousOverflow = document.body.style.overflow;
    document.body.style.overflow = "hidden";
    closeButtonRef.current?.focus();
    return () => {
      document.body.style.overflow = previousOverflow;
      previousFocusRef.current?.focus?.();
    };
  }, [isOpen]);
  useEffect(() => {
    if (!isOpen) return undefined;
    const handleKeyDown = event => {
      if (event.key === "Escape") {
        event.preventDefault();
        closeViewer();
        return;
      }
      if ((event.key === "+" || event.key === "=") && !event.metaKey && !event.ctrlKey) {
        event.preventDefault();
        zoomIn();
        return;
      }
      if (event.key === "-" && !event.metaKey && !event.ctrlKey) {
        event.preventDefault();
        zoomOut();
        return;
      }
      if (event.key !== "Tab" || !dialogRef.current) return;
      const focusable = [...dialogRef.current.querySelectorAll('button:not([disabled]), a[href], [tabindex]:not([tabindex="-1"])')];
      if (focusable.length === 0) return;
      const first = focusable[0];
      const last = focusable[focusable.length - 1];
      if (event.shiftKey && document.activeElement === first) {
        event.preventDefault();
        last.focus();
      } else if (!event.shiftKey && document.activeElement === last) {
        event.preventDefault();
        first.focus();
      }
    };
    window.addEventListener("keydown", handleKeyDown);
    return () => {
      window.removeEventListener("keydown", handleKeyDown);
    };
  }, [closeViewer, isOpen, zoomIn, zoomOut]);
  const startDrag = event => {
    if (event.button !== 0 || !viewportRef.current) return;
    const viewport = viewportRef.current;
    dragRef.current = {
      pointerId: event.pointerId,
      x: event.clientX,
      y: event.clientY,
      scrollLeft: viewport.scrollLeft,
      scrollTop: viewport.scrollTop
    };
    viewport.setPointerCapture(event.pointerId);
    viewport.dataset.dragging = "true";
  };
  const continueDrag = event => {
    const drag = dragRef.current;
    const viewport = viewportRef.current;
    if (!drag || !viewport || drag.pointerId !== event.pointerId) return;
    viewport.scrollLeft = drag.scrollLeft - (event.clientX - drag.x);
    viewport.scrollTop = drag.scrollTop - (event.clientY - drag.y);
  };
  const stopDrag = event => {
    const viewport = viewportRef.current;
    if (viewport?.hasPointerCapture(event.pointerId)) viewport.releasePointerCapture(event.pointerId);
    if (viewport) delete viewport.dataset.dragging;
    dragRef.current = null;
  };
  const activeContentBox = frameMode === "content" ? contentBox : null;
  const activeWidth = activeContentBox?.width ?? width;
  const activeHeight = activeContentBox?.height ?? height;
  const activeRatio = activeWidth / activeHeight;
  const inlineContentBox = measurementStatus === "ready" ? contentBox : null;
  const inlineWidth = inlineContentBox?.width ?? width;
  const inlineHeight = inlineContentBox?.height ?? height;
  const inlineGeometry = {
    aspectRatio: `${inlineWidth} / ${inlineHeight}`,
    maxWidth: `${30 * inlineWidth / inlineHeight}rem`
  };
  const imageStyle = viewMode === "fit" ? {
    aspectRatio: `${activeWidth} / ${activeHeight}`,
    width: "100%",
    maxWidth: `${Math.max(16, activeRatio * 78)}dvh`
  } : {
    aspectRatio: `${activeWidth} / ${activeHeight}`,
    width: `${zoom * 100}%`,
    maxWidth: "none"
  };
  const zoomLabel = viewMode === "fit" ? frameMode === "content" ? "Fit content" : "Full page" : `${Math.round(zoom * 100)}%`;
  return <figure className="latex-preview">
      <button type="button" className="latex-preview__trigger" onClick={openViewer} aria-haspopup="dialog" aria-label={`Open zoomable preview: ${alt}`}>
        <span className="latex-preview__page" style={inlineGeometry}>
          {measurementStatus === "loading" ? <span className="latex-preview__loading" role="status">Preparing compiled output…</span> : renderPreviewAsset({
    src,
    alt,
    width,
    height,
    contentBox: inlineContentBox,
    loading: "lazy"
  })}
        </span>
        <span className="latex-preview__trigger-label" aria-hidden="true">
          <span className="latex-preview__trigger-icon">⌕</span>
          Open viewer
        </span>
      </button>
      <figcaption className="latex-preview__caption">
        <span>
          {caption}
          {measurementStatus === "error" && <span className="latex-preview__status" role="status"> Content fit is unavailable; the complete vector page is shown.</span>}
        </span>
        <a href={src} target="_blank" rel="noreferrer" className="latex-preview__source-link">Open SVG</a>
      </figcaption>

      {isOpen && <div className="latex-preview__backdrop" onMouseDown={event => {
    if (event.target === event.currentTarget) closeViewer();
  }}>
          <section ref={dialogRef} className="latex-preview__dialog" role="dialog" aria-modal="true" aria-label={`Rendered LaTeX viewer: ${alt}`}>
            <header className="latex-preview__toolbar">
              <div className="latex-preview__identity">
                <span className="latex-preview__eyebrow">Compiled LaTeX</span>
                <span className="latex-preview__filename">{alt}</span>
              </div>
              <div className="latex-preview__controls" aria-label="Preview controls">
                <button type="button" className={frameMode === "content" && viewMode === "fit" ? "is-active" : undefined} disabled={!contentBox} onClick={() => {
    setFrameMode("content");
    setViewMode("fit");
    setZoom(minZoom);
  }}>
                  Fit content
                </button>
                <button type="button" className={frameMode === "page" && viewMode === "fit" ? "is-active" : undefined} onClick={() => {
    setFrameMode("page");
    setViewMode("fit");
    setZoom(minZoom);
  }}>
                  Full page
                </button>
                <span className="latex-preview__zoom-group">
                  <button type="button" onClick={zoomOut} disabled={viewMode === "fit" || zoom <= minZoom} aria-label="Zoom out">−</button>
                  <output aria-live="polite" aria-label="Current zoom">{zoomLabel}</output>
                  <button type="button" onClick={zoomIn} disabled={viewMode !== "fit" && zoom >= maxZoom} aria-label="Zoom in">+</button>
                </span>
                <a href={src} target="_blank" rel="noreferrer">Open SVG</a>
                <button ref={closeButtonRef} type="button" className="latex-preview__close" onClick={closeViewer} aria-label="Close rendered LaTeX viewer">
                  Close
                </button>
              </div>
            </header>
            <div ref={viewportRef} className="latex-preview__viewport" data-view-mode={viewMode} onPointerDown={startDrag} onPointerMove={continueDrag} onPointerUp={stopDrag} onPointerCancel={stopDrag}>
              <span className="latex-preview__dialog-page" style={imageStyle}>
                {renderPreviewAsset({
    src,
    alt,
    width,
    height,
    contentBox: activeContentBox
  })}
              </span>
            </div>
            <footer className="latex-preview__viewer-note">
              Compiler-generated vector output · Use +/− to zoom · Drag to pan · Esc to close
            </footer>
          </section>
        </div>}
    </figure>;
};

If you want to create a matrix in LaTeX, the usual answer is to load `amsmath` and use `pmatrix` or `bmatrix`.

Use `pmatrix` for parentheses, `bmatrix` for square brackets, `vmatrix` for determinants, and `smallmatrix` for inline math. When you need vertical separators for an augmented matrix or custom alignment, switch to `array`.

This guide starts with the common matrix environments, then covers augmented matrices, block matrices, spacing, and alignment.

<Info>
  **Quick answer**:

  <LatexSource filename="example.tex" source={"\\usepackage{amsmath}\n\n\\[\nA = \\begin{pmatrix}\n1 & 2 \\\\\n3 & 4\n\\end{pmatrix}\n\\]"} />

  <RenderedOutput title="Rendered output">
    <LatexPreview src="/images/rendered/learn-latex-mathematics-matrices-15/page-1.svg" alt="Compiled PDF page 1 from example.tex" caption="Generated from the shown source with pdfLaTeX in the pinned LaTeXCloud TeX Live 2026 environment. The visible fragment is compiled inside the documented minimal article wrapper." width={595.276} height={841.89} />
  </RenderedOutput>

  Use `pmatrix` for `( )`, `bmatrix` for `[ ]`, and `vmatrix` for determinants.

  **Package required**: Most matrix environments need `\usepackage{amsmath}`. Some advanced layouts also use `array` or `mathtools`.

  **Related topics**: [Mathematical equations](/learn/latex/mathematics/equations) | [Subscripts & superscripts](/learn/latex/mathematics/subscripts-superscripts) | [Brackets & parentheses](/learn/latex/mathematics/brackets-parentheses) | [LaTeX symbols](/learn/latex/mathematics/symbols)

  **Last updated**: April 2026 | **Reading time**: 15 min | **Difficulty**: Beginner to Intermediate
</Info>

## What You'll Learn

* ✅ All LaTeX matrix environments (pmatrix, bmatrix, vmatrix, Bmatrix, Vmatrix)
* ✅ Creating arrays with custom delimiters and column alignment
* ✅ Block matrices and augmented matrix notation
* ✅ Matrix operations, determinants, and transpose notation
* ✅ Small inline matrices with smallmatrix environment
* ✅ Advanced matrix formatting, spacing, and decorations
* ✅ Troubleshooting common LaTeX matrix issues

## Frequently Asked Questions

<Accordion title="What is the difference between pmatrix and bmatrix in LaTeX?">
  The main difference between `pmatrix` and `bmatrix` is the type of **delimiters** (brackets) they use:

  * **pmatrix** uses **parentheses** ( ) - most common for general matrices in mathematics
  * **bmatrix** uses **square brackets** \[ ] - preferred for numerical data and engineering

  Both require the `amsmath` package and work identically in terms of syntax:

  <LatexSource filename="example.tex" source={"% Using pmatrix (parentheses)\n$A = \\begin{pmatrix} 1 & 2 \\\\ 3 & 4 \\end{pmatrix}$\n\n% Using bmatrix (square brackets)\n$B = \\begin{bmatrix} 1 & 2 \\\\ 3 & 4 \\end{bmatrix}$"} />

  <RenderedOutput title="Rendered output">
    <LatexPreview src="/images/rendered/learn-latex-mathematics-matrices-16/page-1.svg" alt="Compiled PDF page 1 from example.tex" caption="Generated from the shown source with pdfLaTeX in the pinned LaTeXCloud TeX Live 2026 environment. The visible fragment is compiled inside the documented minimal article wrapper." width={595.276} height={841.89} />
  </RenderedOutput>

  **When to use each:**

  * Use **pmatrix** for: linear transformations, general matrices, mathematical proofs
  * Use **bmatrix** for: numerical data, matrices in data science, engineering applications
  * Use **vmatrix** for: determinants (single vertical bars)
</Accordion>

<Accordion title="How do I create a matrix with vertical lines between columns (augmented matrix)?">
  To create an **augmented matrix** with vertical lines separating columns, use the `array` environment with the pipe symbol `|` in the column specification:

  <LatexSource filename="example.tex" source={"\\[\n\\left[\\begin{array}{cc|c}\n1 & 2 & 5 \\\\\n3 & 4 & 11\n\\end{array}\\right]\n\\]"} />

  <RenderedOutput title="Rendered output">
    <LatexPreview src="/images/rendered/learn-latex-mathematics-matrices-17/page-1.svg" alt="Compiled PDF page 1 from example.tex" caption="Generated from the shown source with pdfLaTeX in the pinned LaTeXCloud TeX Live 2026 environment. The visible fragment is compiled inside the documented minimal article wrapper." width={595.276} height={841.89} />
  </RenderedOutput>

  **How it works:**

  * `{cc|c}` means: column-center, column-center, **vertical line**, column-center
  * Use `c` for centered, `l` for left-aligned, `r` for right-aligned
  * The pipe `|` symbol creates the vertical separator line
  * Use `\left[` and `\right]` to automatically scale brackets
</Accordion>

<Accordion title="What is the amsmath package and why do I need it for LaTeX matrices?">
  The **amsmath** package (American Mathematical Society) provides essential **matrix environments** that aren't available in plain LaTeX:

  * `pmatrix` (parentheses)
  * `bmatrix` (square brackets)
  * `vmatrix` (determinant notation)
  * `Vmatrix` (norm notation)
  * `Bmatrix` (curly braces)
  * `smallmatrix` (inline matrices)

  **How to load it:**

  <LatexSource filename="example.tex" source={"\\documentclass{article}\n\\usepackage{amsmath}"} />

  <RenderedOutput title="Expected effect">
    <Info>
      This is setup or structural LaTeX code. It changes available commands or document behavior, but it does not produce meaningful standalone page content by itself.
    </Info>
  </RenderedOutput>

  Without amsmath, you'd be limited to the basic `array` environment with manual delimiter management.
</Accordion>

<Accordion title="How do I fix alignment issues with numbers in LaTeX matrices?">
  **Number alignment problems** occur when columns contain different-width numbers. Use these solutions:

  **Solution 1: Right-aligned array**

  <LatexSource filename="example.tex" source={"\\left[\\begin{array}{rr}\n1.2 & 345.6 \\\\\n12.34 & 5.6\n\\end{array}\\right]"} />

  <RenderedOutput title="Rendered output">
    <LatexPreview src="/images/rendered/learn-latex-mathematics-matrices-19/page-1.svg" alt="Compiled PDF page 1 from example.tex" caption="Generated from the shown source with pdfLaTeX in the pinned LaTeXCloud TeX Live 2026 environment. The visible fragment is compiled inside the documented minimal article wrapper." width={595.276} height={841.89} />
  </RenderedOutput>

  **Solution 2: Use siunitx for decimal alignment**

  <LatexSource filename="example.tex" source={"\\usepackage{siunitx}\n\\begin{array}{SS}\n1.2 & 345.6 \\\\\n12.34 & 5.6\n\\end{array}"} />

  <RenderedOutput title="Rendered output">
    <LatexPreview src="/images/rendered/learn-latex-mathematics-matrices-20/page-1.svg" alt="Compiled PDF page 1 from example.tex" caption="Generated from the shown source with pdfLaTeX in the pinned LaTeXCloud TeX Live 2026 environment. The visible fragment is compiled inside the documented minimal article wrapper." width={612} height={792} />
  </RenderedOutput>

  **Solution 3: Use phantom spacing**

  <LatexSource filename="example.tex" source={"\\phantom{0}1.2  % Adds invisible space"} />

  <RenderedOutput title="Rendered output">
    <LatexPreview src="/images/rendered/learn-latex-mathematics-matrices-21/page-1.svg" alt="Compiled PDF page 1 from example.tex" caption="Generated from the shown source with pdfLaTeX in the pinned LaTeXCloud TeX Live 2026 environment. The visible fragment is compiled inside the documented minimal article wrapper." width={595.276} height={841.89} />
  </RenderedOutput>
</Accordion>

<Accordion title="How do I create a small inline matrix in LaTeX?">
  For **matrices within text paragraphs**, use the `smallmatrix` environment:

  <LatexSource filename="example.tex" source={"The rotation matrix $\\left(\\begin{smallmatrix}\n\\cos\\theta & -\\sin\\theta \\\\\n\\sin\\theta & \\cos\\theta\n\\end{smallmatrix}\\right)$ transforms points in 2D space."} />

  <RenderedOutput title="Rendered output">
    <LatexPreview src="/images/rendered/learn-latex-mathematics-matrices-22/page-1.svg" alt="Compiled PDF page 1 from example.tex" caption="Generated from the shown source with pdfLaTeX in the pinned LaTeXCloud TeX Live 2026 environment. The visible fragment is compiled inside the documented minimal article wrapper." width={595.276} height={841.89} />
  </RenderedOutput>

  Regular `pmatrix` environments are too large for inline use and disrupt line spacing. The `smallmatrix` environment uses smaller fonts and tighter spacing.
</Accordion>

<Accordion title="What does the array column specifier mean in LaTeX matrices?">
  **Column specifiers** define how each column is formatted:

  | Specifier | Alignment        | Example  |
  | --------- | ---------------- | -------- |
  | `l`       | Left             | `{lll}`  |
  | `c`       | Center           | `{ccc}`  |
  | `r`       | Right            | `{rrr}`  |
  | `\|`      | Vertical line    | `{c\|c}` |
  | `@{text}` | Custom separator | `@{,}`   |

  Example with vertical line:

  <LatexSource filename="example.tex" source={"\\begin{array}{cc|c}\n1 & 2 & 5 \\\\\n3 & 4 & 11\n\\end{array}"} />

  <RenderedOutput title="Rendered output">
    <LatexPreview src="/images/rendered/learn-latex-mathematics-matrices-23/page-1.svg" alt="Compiled PDF page 1 from example.tex" caption="Generated from the shown source with pdfLaTeX in the pinned LaTeXCloud TeX Live 2026 environment. The visible fragment is compiled inside the documented minimal article wrapper." width={595.276} height={841.89} />
  </RenderedOutput>
</Accordion>

<Accordion title="How do I calculate and display a determinant in LaTeX?">
  Use the `vmatrix` environment for **determinant notation** with vertical bar delimiters:

  <LatexSource filename="example.tex" source={"\\det(A) = \\begin{vmatrix}\na & b \\\\\nc & d\n\\end{vmatrix} = ad - bc"} />

  <RenderedOutput title="Rendered output">
    <LatexPreview src="/images/rendered/learn-latex-mathematics-matrices-24/page-1.svg" alt="Compiled PDF page 1 from example.tex" caption="Generated from the shown source with pdfLaTeX in the pinned LaTeXCloud TeX Live 2026 environment. The visible fragment is compiled inside the documented minimal article wrapper." width={595.276} height={841.89} />
  </RenderedOutput>

  For 3×3 matrices:

  <LatexSource filename="example.tex" source={"\\begin{vmatrix}\na_{11} & a_{12} & a_{13} \\\\\na_{21} & a_{22} & a_{23} \\\\\na_{31} & a_{32} & a_{33}\n\\end{vmatrix}"} />

  <RenderedOutput title="Rendered output">
    <LatexPreview src="/images/rendered/learn-latex-mathematics-matrices-25/page-1.svg" alt="Compiled PDF page 1 from example.tex" caption="Generated from the shown source with pdfLaTeX in the pinned LaTeXCloud TeX Live 2026 environment. The visible fragment is compiled inside the documented minimal article wrapper." width={595.276} height={841.89} />
  </RenderedOutput>
</Accordion>

<Accordion title="How do I increase spacing between elements in a LaTeX matrix?">
  Use `\renewcommand{\arraystretch}{factor}` to control **matrix element spacing**:

  <LatexSource filename="example.tex" source={"% 50% more space between rows\n{\\renewcommand{\\arraystretch}{1.5}\n$\\begin{pmatrix}\na & b \\\\\nc & d\n\\end{pmatrix}$}"} />

  <RenderedOutput title="Rendered output">
    <LatexPreview src="/images/rendered/learn-latex-mathematics-matrices-26/page-1.svg" alt="Compiled PDF page 1 from example.tex" caption="Generated from the shown source with pdfLaTeX in the pinned LaTeXCloud TeX Live 2026 environment. The visible fragment is compiled inside the documented minimal article wrapper." width={595.276} height={841.89} />
  </RenderedOutput>

  **Recommended values:**

  * `1.0` - Default compact spacing
  * `1.2` - Standard matrices
  * `1.5` - Matrices with fractions or subscripts
  * `2.0` - Matrices with tall expressions

  Use curly braces to limit the effect to just one matrix.
</Accordion>

## Basic Matrix Environments

LaTeX provides six standard matrix environments through the `amsmath` package, each with different delimiters:

### Matrix Environment Overview

<LatexSource filename="all-matrix-types.tex" source={"\\documentclass{article}\n\\usepackage{amsmath}\n\\begin{document}\n\n% Parentheses matrix (most common)\n$\\begin{pmatrix}\na & b \\\\\nc & d\n\\end{pmatrix}$\n\n% Square bracket matrix\n$\\begin{bmatrix}\n1 & 2 & 3 \\\\\n4 & 5 & 6 \\\\\n7 & 8 & 9\n\\end{bmatrix}$\n\n% Curly brace matrix\n$\\begin{Bmatrix}\nx_1 \\\\\nx_2 \\\\\nx_3\n\\end{Bmatrix}$\n\n% Determinant (vertical bars)\n$\\begin{vmatrix}\na & b \\\\\nc & d\n\\end{vmatrix} = ad - bc$\n\n% Norm (double vertical bars)\n$\\begin{Vmatrix}\n\\mathbf{v}\n\\end{Vmatrix} = \\begin{Vmatrix}\n1 & 2 \\\\\n3 & 4\n\\end{Vmatrix}$\n\n% No delimiters\n$\\begin{matrix}\na & b \\\\\nc & d\n\\end{matrix}$\n\n\\end{document}"} />

<RenderedOutput title="Rendered output" ctaHref="https://app.latex-cloud-studio.com/?utm_source=resources&utm_medium=rendered_output&utm_campaign=docs_open_app&utm_content=learn_latex_mathematics_matrices">
  <LatexPreview src="/images/rendered/learn-latex-mathematics-matrices-01/page-1.svg" alt="Compiled PDF page 1 from all-matrix-types.tex" caption="Generated from the shown source with pdfLaTeX in the pinned LaTeXCloud TeX Live 2026 environment." width={595.276} height={841.89} />
</RenderedOutput>

### Matrix Environment Summary Table

| Environment | Delimiters | Common Use                           | Example        |
| ----------- | ---------- | ------------------------------------ | -------------- |
| `matrix`    | None       | Building block for custom delimiters | Basic array    |
| `pmatrix`   | ( )        | General matrices, transformations    | Linear algebra |
| `bmatrix`   | \[ ]       | General matrices, data tables        | Numerical data |
| `Bmatrix`   | { }        | Set notation, systems                | Set theory     |
| `vmatrix`   | \| \|      | Determinants                         | det(A)         |
| `Vmatrix`   | \|\| \|\|  | Norms, magnitudes                    | \|\|v\|\|      |

## Creating Your First Matrix

### Simple 2×2 Matrix

<LatexSource filename="simple-matrix.tex" source={"\\documentclass{article}\n\\usepackage{amsmath}\n\\begin{document}\n\n% Basic 2x2 matrix\nThe matrix $A = \\begin{pmatrix}\n1 & 2 \\\\\n3 & 4\n\\end{pmatrix}$ is invertible.\n\n% With variables\nThe general form is $\\begin{pmatrix}\na & b \\\\\nc & d\n\\end{pmatrix}$ where $ad - bc \\neq 0$.\n\n% Matrix equation\n$\\begin{pmatrix}\n2 & 1 \\\\\n1 & 3\n\\end{pmatrix}\n\\begin{pmatrix}\nx \\\\\ny\n\\end{pmatrix}\n=\n\\begin{pmatrix}\n5 \\\\\n7\n\\end{pmatrix}$\n\n\\end{document}"} />

<RenderedOutput title="Rendered output">
  <LatexPreview src="/images/rendered/learn-latex-mathematics-matrices-02/page-1.svg" alt="Compiled PDF page 1 from simple-matrix.tex" caption="Generated from the shown source with pdfLaTeX in the pinned LaTeXCloud TeX Live 2026 environment." width={595.276} height={841.89} />
</RenderedOutput>

<Tip>
  **Key points for matrix creation:**

  * Use `&` to separate columns
  * Use `\\` to end rows
  * Don't add `\\` after the last row
  * Matrices must be in math mode (`$...$` or `\[...\]`)
</Tip>

## Matrix Elements and Structure

### Matrix with Subscripts

<LatexSource filename="matrix-subscripts.tex" source={"\\documentclass{article}\n\\usepackage{amsmath}\n\\begin{document}\n\n% General m×n matrix\n$A = \\begin{pmatrix}\na_{11} & a_{12} & \\cdots & a_{1n} \\\\\na_{21} & a_{22} & \\cdots & a_{2n} \\\\\n\\vdots & \\vdots & \\ddots & \\vdots \\\\\na_{m1} & a_{m2} & \\cdots & a_{mn}\n\\end{pmatrix}$\n\n% 3×3 example\n$B = \\begin{bmatrix}\nb_{11} & b_{12} & b_{13} \\\\\nb_{21} & b_{22} & b_{23} \\\\\nb_{31} & b_{32} & b_{33}\n\\end{bmatrix}$\n\n% Column vector\n$\\mathbf{x} = \\begin{pmatrix}\nx_1 \\\\\nx_2 \\\\\nx_3 \\\\\n\\vdots \\\\\nx_n\n\\end{pmatrix}$\n\n% Row vector\n$\\mathbf{y}^T = \\begin{pmatrix}\ny_1 & y_2 & y_3 & \\cdots & y_n\n\\end{pmatrix}$\n\n\\end{document}"} />

<RenderedOutput title="Rendered output">
  <LatexPreview src="/images/rendered/learn-latex-mathematics-matrices-03/page-1.svg" alt="Compiled PDF page 1 from matrix-subscripts.tex" caption="Generated from the shown source with pdfLaTeX in the pinned LaTeXCloud TeX Live 2026 environment." width={595.276} height={841.89} />
</RenderedOutput>

### Using Dots in Matrices

LaTeX provides three types of dots for indicating patterns in matrices:

<LatexSource filename="matrix-dots.tex" source={"\\documentclass{article}\n\\usepackage{amsmath}\n\\begin{document}\n\n% Horizontal dots: \\cdots\n% Vertical dots: \\vdots  \n% Diagonal dots: \\ddots\n\n% General matrix pattern\n$\\begin{bmatrix}\na_{11} & a_{12} & \\cdots & a_{1n} \\\\\na_{21} & a_{22} & \\cdots & a_{2n} \\\\\n\\vdots & \\vdots & \\ddots & \\vdots \\\\\na_{m1} & a_{m2} & \\cdots & a_{mn}\n\\end{bmatrix}$\n\n% Diagonal matrix\n$D = \\begin{bmatrix}\nd_1 & 0 & \\cdots & 0 \\\\\n0 & d_2 & \\ddots & \\vdots \\\\\n\\vdots & \\ddots & \\ddots & 0 \\\\\n0 & \\cdots & 0 & d_n\n\\end{bmatrix}$\n\n% Block pattern\n$\\begin{pmatrix}\nA_{11} & A_{12} & \\cdots & A_{1n} \\\\\nA_{21} & A_{22} & \\cdots & A_{2n} \\\\\n\\vdots & \\vdots & \\ddots & \\vdots \\\\\nA_{m1} & A_{m2} & \\cdots & A_{mn}\n\\end{pmatrix}$\n\n\\end{document}"} />

<RenderedOutput title="Rendered output">
  <LatexPreview src="/images/rendered/learn-latex-mathematics-matrices-04/page-1.svg" alt="Compiled PDF page 1 from matrix-dots.tex" caption="Generated from the shown source with pdfLaTeX in the pinned LaTeXCloud TeX Live 2026 environment." width={595.276} height={841.89} />
</RenderedOutput>

## Special Matrix Types

### Identity and Zero Matrices

<LatexSource filename="special-matrices.tex" source={"\\documentclass{article}\n\\usepackage{amsmath}\n\\begin{document}\n\n% Identity matrix\n$I_3 = \\begin{pmatrix}\n1 & 0 & 0 \\\\\n0 & 1 & 0 \\\\\n0 & 0 & 1\n\\end{pmatrix}$\n\n% General identity\n$I_n = \\begin{pmatrix}\n1 & 0 & \\cdots & 0 \\\\\n0 & 1 & \\cdots & 0 \\\\\n\\vdots & \\vdots & \\ddots & \\vdots \\\\\n0 & 0 & \\cdots & 1\n\\end{pmatrix}$\n\n% Zero matrix\n$\\mathbf{0}_{3 \\times 3} = \\begin{pmatrix}\n0 & 0 & 0 \\\\\n0 & 0 & 0 \\\\\n0 & 0 & 0\n\\end{pmatrix}$\n\n% Ones matrix\n$\\mathbf{1}_{2 \\times 3} = \\begin{pmatrix}\n1 & 1 & 1 \\\\\n1 & 1 & 1\n\\end{pmatrix}$\n\n\\end{document}"} />

<RenderedOutput title="Rendered output">
  <LatexPreview src="/images/rendered/learn-latex-mathematics-matrices-05/page-1.svg" alt="Compiled PDF page 1 from special-matrices.tex" caption="Generated from the shown source with pdfLaTeX in the pinned LaTeXCloud TeX Live 2026 environment." width={595.276} height={841.89} />
</RenderedOutput>

### Triangular Matrices

<LatexSource filename="triangular-matrices.tex" source={"\\documentclass{article}\n\\usepackage{amsmath}\n\\begin{document}\n\n% Upper triangular\n$U = \\begin{pmatrix}\nu_{11} & u_{12} & u_{13} & u_{14} \\\\\n0 & u_{22} & u_{23} & u_{24} \\\\\n0 & 0 & u_{33} & u_{34} \\\\\n0 & 0 & 0 & u_{44}\n\\end{pmatrix}$\n\n% Lower triangular\n$L = \\begin{pmatrix}\nl_{11} & 0 & 0 & 0 \\\\\nl_{21} & l_{22} & 0 & 0 \\\\\nl_{31} & l_{32} & l_{33} & 0 \\\\\nl_{41} & l_{42} & l_{43} & l_{44}\n\\end{pmatrix}$\n\n% Strictly upper triangular\n$U_0 = \\begin{pmatrix}\n0 & u_{12} & u_{13} \\\\\n0 & 0 & u_{23} \\\\\n0 & 0 & 0\n\\end{pmatrix}$\n\n% Tridiagonal\n$T = \\begin{pmatrix}\na_1 & b_1 & 0 & 0 \\\\\nc_1 & a_2 & b_2 & 0 \\\\\n0 & c_2 & a_3 & b_3 \\\\\n0 & 0 & c_3 & a_4\n\\end{pmatrix}$\n\n\\end{document}"} />

<RenderedOutput title="Rendered output">
  <LatexPreview src="/images/rendered/learn-latex-mathematics-matrices-06/page-1.svg" alt="Compiled PDF page 1 from triangular-matrices.tex" caption="Generated from the shown source with pdfLaTeX in the pinned LaTeXCloud TeX Live 2026 environment." width={595.276} height={841.89} />
</RenderedOutput>

## Arrays - The Foundation of Matrices

The `array` environment provides the most flexibility for creating custom matrix-like structures:

### Basic Array Usage

<LatexSource filename="array-basics.tex" source={"\\documentclass{article}\n\\usepackage{amsmath}\n\\begin{document}\n\n% Basic array with alignment\n$\\begin{array}{crl}\n\\text{center} & \\text{right} & \\text{left} \\\\\na + b & 12.34 & xyz \\\\\nc & 5.6 & pqrs\n\\end{array}$\n\n% Array with vertical lines\n$\\left[\\begin{array}{c|cc|c}\n1 & 2 & 3 & 4 \\\\\n\\hline\n5 & 6 & 7 & 8\n\\end{array}\\right]$\n\n% Custom spacing\n$\\begin{array}{r@{\\,}c@{\\,}l}\nx &=& 2y + 3z \\\\\n2x - y &=& 7 \\\\\nx + 3y &=& 4z - 1\n\\end{array}$\n\n% Mixed content\n$\\begin{array}{|l|c|}\n\\hline\n\\text{Type} & \\text{Matrix} \\\\\n\\hline\n\\text{Identity} & \\begin{pmatrix} 1 & 0 \\\\ 0 & 1 \\end{pmatrix} \\\\\n\\hline\n\\text{Zero} & \\begin{pmatrix} 0 & 0 \\\\ 0 & 0 \\end{pmatrix} \\\\\n\\hline\n\\end{array}$\n\n\\end{document}"} />

<RenderedOutput title="Rendered output">
  <LatexPreview src="/images/rendered/learn-latex-mathematics-matrices-07/page-1.svg" alt="Compiled PDF page 1 from array-basics.tex" caption="Generated from the shown source with pdfLaTeX in the pinned LaTeXCloud TeX Live 2026 environment." width={595.276} height={841.89} />
</RenderedOutput>

### Array Column Specifiers

| Specifier    | Alignment | Description                                 |                               |
| ------------ | --------- | ------------------------------------------- | ----------------------------- |
| `l`          | Left      | Left-aligned column                         |                               |
| `c`          | Center    | Centered column                             |                               |
| `r`          | Right     | Right-aligned column                        |                               |
| `p{width}`   | Paragraph | Fixed width with text wrapping              |                               |
| \`           | \`        | —                                           | Vertical line between columns |
| `@{text}`    | —         | Custom separator (replaces default spacing) |                               |
| `*{n}{spec}` | —         | Repeat specifier n times                    |                               |

## Block Matrices

Block matrices are used to partition large matrices into smaller submatrices:

### Basic Block Matrices

<LatexSource filename="block-matrices.tex" source={"\\documentclass{article}\n\\usepackage{amsmath}\n\\begin{document}\n\n% Simple 2×2 block matrix\n$M = \\begin{pmatrix}\nA & B \\\\\nC & D\n\\end{pmatrix}$\n\n% With array for lines\n$\\left[\\begin{array}{c|c}\nA & B \\\\\n\\hline\nC & D\n\\end{array}\\right]$\n\n% Detailed block matrix\n$\\begin{pmatrix}\n\\begin{matrix}\na_{11} & a_{12} \\\\\na_{21} & a_{22}\n\\end{matrix} & \n\\begin{matrix}\nb_{11} & b_{12} \\\\\nb_{21} & b_{22}\n\\end{matrix} \\\\[1em]\n\\begin{matrix}\nc_{11} & c_{12} \\\\\nc_{21} & c_{22}\n\\end{matrix} & \n\\begin{matrix}\nd_{11} & d_{12} \\\\\nd_{21} & d_{22}\n\\end{matrix}\n\\end{pmatrix}$\n\n% Mixed size blocks\n$\\begin{pmatrix}\nA_{2 \\times 2} & \\mathbf{b}_{2 \\times 1} \\\\\n\\mathbf{c}_{1 \\times 2} & d_{1 \\times 1}\n\\end{pmatrix}\n= \n\\begin{pmatrix}\n\\begin{matrix}\na & b \\\\\nc & d\n\\end{matrix} & \\begin{matrix} e \\\\ f \\end{matrix} \\\\[0.5em]\n\\begin{matrix} g & h \\end{matrix} & i\n\\end{pmatrix}$\n\n\\end{document}"} />

<RenderedOutput title="Rendered output">
  <LatexPreview src="/images/rendered/learn-latex-mathematics-matrices-08/page-1.svg" alt="Compiled PDF page 1 from block-matrices.tex" caption="Generated from the shown source with pdfLaTeX in the pinned LaTeXCloud TeX Live 2026 environment." width={595.276} height={841.89} />
</RenderedOutput>

## Augmented Matrices

Augmented matrices are commonly used for solving systems of linear equations:

<LatexSource filename="augmented-matrices.tex" source={"\\documentclass{article}\n\\usepackage{amsmath}\n\\begin{document}\n\n% Basic augmented matrix\n$\\left[\\begin{array}{ccc|c}\n1 & 2 & 3 & 6 \\\\\n4 & 5 & 6 & 15 \\\\\n7 & 8 & 9 & 24\n\\end{array}\\right]$\n\n% Row reduction example\n$\\left[\\begin{array}{rrr|r}\n1 & 2 & -1 & 3 \\\\\n2 & -1 & 3 & 7 \\\\\n-1 & 3 & 2 & 0\n\\end{array}\\right]\n\\xrightarrow{R_2 - 2R_1}\n\\left[\\begin{array}{rrr|r}\n1 & 2 & -1 & 3 \\\\\n0 & -5 & 5 & 1 \\\\\n-1 & 3 & 2 & 0\n\\end{array}\\right]$\n\n% Extended augmentation\n$\\left[\\begin{array}{cc|c|cc}\na & b & e & 1 & 0 \\\\\nc & d & f & 0 & 1\n\\end{array}\\right]$\n\n\\end{document}"} />

<RenderedOutput title="Rendered output">
  <LatexPreview src="/images/rendered/learn-latex-mathematics-matrices-09/page-1.svg" alt="Compiled PDF page 1 from augmented-matrices.tex" caption="Generated from the shown source with pdfLaTeX in the pinned LaTeXCloud TeX Live 2026 environment." width={595.276} height={841.89} />
</RenderedOutput>

## Matrix Operations

### Basic Operations Notation

<LatexSource filename="matrix-operations.tex" source={"\\documentclass{article}\n\\usepackage{amsmath}\n\\begin{document}\n\n% Matrix multiplication\n$AB = \\begin{pmatrix}\na & b \\\\\nc & d\n\\end{pmatrix}\n\\begin{pmatrix}\ne & f \\\\\ng & h\n\\end{pmatrix}\n= \\begin{pmatrix}\nae + bg & af + bh \\\\\nce + dg & cf + dh\n\\end{pmatrix}$\n\n% Transpose\n$A^T = \\begin{pmatrix}\n1 & 2 & 3 \\\\\n4 & 5 & 6\n\\end{pmatrix}^T\n= \\begin{pmatrix}\n1 & 4 \\\\\n2 & 5 \\\\\n3 & 6\n\\end{pmatrix}$\n\n% Inverse (2×2 formula)\n$A^{-1} = \\begin{pmatrix}\na & b \\\\\nc & d\n\\end{pmatrix}^{-1}\n= \\frac{1}{ad-bc}\n\\begin{pmatrix}\nd & -b \\\\\n-c & a\n\\end{pmatrix}$\n\n% Matrix power\n$A^2 = AA = \\begin{pmatrix}\n1 & 2 \\\\\n3 & 4\n\\end{pmatrix}^2\n= \\begin{pmatrix}\n7 & 10 \\\\\n15 & 22\n\\end{pmatrix}$\n\n\\end{document}"} />

<RenderedOutput title="Rendered output">
  <LatexPreview src="/images/rendered/learn-latex-mathematics-matrices-10/page-1.svg" alt="Compiled PDF page 1 from matrix-operations.tex" caption="Generated from the shown source with pdfLaTeX in the pinned LaTeXCloud TeX Live 2026 environment." width={595.276} height={841.89} />
</RenderedOutput>

### Determinants and Traces

<LatexSource filename="determinants.tex" source={"\\documentclass{article}\n\\usepackage{amsmath}\n\\begin{document}\n\n% 2×2 determinant\n$\\det(A) = \\begin{vmatrix}\na & b \\\\\nc & d\n\\end{vmatrix} = ad - bc$\n\n% 3×3 determinant\n$\\begin{vmatrix}\na_{11} & a_{12} & a_{13} \\\\\na_{21} & a_{22} & a_{23} \\\\\na_{31} & a_{32} & a_{33}\n\\end{vmatrix}$\n\n% Alternative notations\n$|A| = \\det(A) = \\det\\begin{pmatrix}\n1 & 2 \\\\\n3 & 4\n\\end{pmatrix} = -2$\n\n% Trace\n$\\text{tr}(A) = \\sum_{i=1}^n a_{ii} = a_{11} + a_{22} + \\cdots + a_{nn}$\n\n% Example\n$\\text{tr}\\begin{pmatrix}\n5 & 2 & 1 \\\\\n3 & 7 & 4 \\\\\n6 & 8 & 9\n\\end{pmatrix} = 5 + 7 + 9 = 21$\n\n\\end{document}"} />

<RenderedOutput title="Rendered output">
  <LatexPreview src="/images/rendered/learn-latex-mathematics-matrices-11/page-1.svg" alt="Compiled PDF page 1 from determinants.tex" caption="Generated from the shown source with pdfLaTeX in the pinned LaTeXCloud TeX Live 2026 environment." width={595.276} height={841.89} />
</RenderedOutput>

## Small Inline Matrices

For matrices within text, use the `smallmatrix` environment:

<LatexSource filename="inline-matrices.tex" source={"\\documentclass{article}\n\\usepackage{amsmath}\n\\begin{document}\n\n% Inline matrix in text\nThe rotation matrix $\\left(\\begin{smallmatrix}\n\\cos\\theta & -\\sin\\theta \\\\\n\\sin\\theta & \\cos\\theta\n\\end{smallmatrix}\\right)$ rotates vectors by angle $\\theta$.\n\n% Pauli matrices\nThe Pauli matrices are \n$\\sigma_x = \\left(\\begin{smallmatrix}\n0 & 1 \\\\\n1 & 0\n\\end{smallmatrix}\\right)$,\n$\\sigma_y = \\left(\\begin{smallmatrix}\n0 & -i \\\\\ni & 0\n\\end{smallmatrix}\\right)$, and\n$\\sigma_z = \\left(\\begin{smallmatrix}\n1 & 0 \\\\\n0 & -1\n\\end{smallmatrix}\\right)$.\n\n% Custom command for convenience\n\\newcommand{\\mat}[1]{\\left(\\begin{smallmatrix}#1\\end{smallmatrix}\\right)}\nThen we can write $A = \\mat{a & b \\\\ c & d}$ inline.\n\n\\end{document}"} />

<RenderedOutput title="Rendered output">
  <LatexPreview src="/images/rendered/learn-latex-mathematics-matrices-12/page-1.svg" alt="Compiled PDF page 1 from inline-matrices.tex" caption="Generated from the shown source with pdfLaTeX in the pinned LaTeXCloud TeX Live 2026 environment." width={595.276} height={841.89} />
</RenderedOutput>

## Advanced Techniques

### Matrices with Labels

<LatexSource filename="labeled-matrices.tex" source={"\\documentclass{article}\n\\usepackage{amsmath}\n\\usepackage{blkarray} % For labeled matrices\n\\begin{document}\n\n% Using array for labels\n$\\begin{array}{c|ccc}\n& \\text{Col 1} & \\text{Col 2} & \\text{Col 3} \\\\\n\\hline\n\\text{Row 1} & a_{11} & a_{12} & a_{13} \\\\\n\\text{Row 2} & a_{21} & a_{22} & a_{23} \\\\\n\\text{Row 3} & a_{31} & a_{32} & a_{33}\n\\end{array}$\n\n% Using blkarray package\n$\\begin{blockarray}{cccc}\n& x_1 & x_2 & x_3 \\\\\n\\begin{block}{c(ccc)}\ny_1 & 0.8 & 0.1 & 0.1 \\\\\ny_2 & 0.2 & 0.7 & 0.1 \\\\\ny_3 & 0.1 & 0.2 & 0.7 \\\\\n\\end{block}\n\\end{blockarray}$\n\n% Correlation matrix example\n$R = \\begin{array}{c|ccc}\n& X & Y & Z \\\\\n\\hline\nX & 1.00 & 0.85 & 0.42 \\\\\nY & 0.85 & 1.00 & 0.67 \\\\\nZ & 0.42 & 0.67 & 1.00\n\\end{array}$\n\n\\end{document}"} />

<RenderedOutput title="Rendered output">
  <LatexPreview src="/images/rendered/learn-latex-mathematics-matrices-13/page-1.svg" alt="Compiled PDF page 1 from labeled-matrices.tex" caption="Generated from the shown source with pdfLaTeX in the pinned LaTeXCloud TeX Live 2026 environment." width={595.276} height={841.89} />
</RenderedOutput>

### Matrix Decorations

<LatexSource filename="matrix-decorations.tex" source={"\\documentclass{article}\n\\usepackage{amsmath}\n\\usepackage{color}\n\\begin{document}\n\n% Highlighting diagonal elements\n$\\begin{pmatrix}\n\\color{red}1 & 0 & 0 \\\\\n0 & \\color{red}2 & 0 \\\\\n0 & 0 & \\color{red}3\n\\end{pmatrix}$\n\n% Boxed elements\n$\\begin{pmatrix}\n\\boxed{1} & 0 & 0 \\\\\n0 & \\boxed{1} & 0 \\\\\n0 & 0 & \\boxed{1}\n\\end{pmatrix}$\n\n% Matrix equation with decorations\n$\\underbrace{\\begin{pmatrix}\n2 & 1 \\\\\n1 & 3\n\\end{pmatrix}}_{A}\n\\underbrace{\\begin{pmatrix}\nx \\\\\ny\n\\end{pmatrix}}_{\\mathbf{x}}\n=\n\\underbrace{\\begin{pmatrix}\n5 \\\\\n7\n\\end{pmatrix}}_{\\mathbf{b}}$\n\n% Annotated matrix\n$\\left(\\begin{array}{ccc}\na_{11} & a_{12} & a_{13} \\\\\na_{21} & a_{22} & a_{23} \\\\\na_{31} & a_{32} & a_{33}\n\\end{array}\\right)\n\\begin{array}{l}\n\\leftarrow \\text{row 1} \\\\\n\\leftarrow \\text{row 2} \\\\\n\\leftarrow \\text{row 3}\n\\end{array}$\n\n\\end{document}"} />

<RenderedOutput title="Rendered output">
  <LatexPreview src="/images/rendered/learn-latex-mathematics-matrices-14/page-1.svg" alt="Compiled PDF page 1 from matrix-decorations.tex" caption="Generated from the shown source with pdfLaTeX in the pinned LaTeXCloud TeX Live 2026 environment." width={612} height={792} />
</RenderedOutput>

## Common Pitfalls and Solutions

<Accordion title="My matrix delimiters are too small">
  **Problem**: Parentheses/brackets don't scale with matrix size.

  **Solution**: Use `\left` and `\right` with array:

  <LatexSource filename="example.tex" source={"$\\left(\\begin{array}{cc}\na & b \\\\\nc & d\n\\end{array}\\right)$"} />

  <RenderedOutput title="Rendered output">
    <LatexPreview src="/images/rendered/learn-latex-mathematics-matrices-27/page-1.svg" alt="Compiled PDF page 1 from example.tex" caption="Generated from the shown source with pdfLaTeX in the pinned LaTeXCloud TeX Live 2026 environment. The visible fragment is compiled inside the documented minimal article wrapper." width={595.276} height={841.89} />
  </RenderedOutput>

  Or use the pre-defined environments like `pmatrix` which handle this automatically.
</Accordion>

<Accordion title="Alignment issues in matrices">
  **Problem**: Numbers don't align properly in columns.

  **Solution**:

  1. Use `array` with explicit alignment: `{rrr}` for right-aligned
  2. For decimals, use the `siunitx` package with `S` columns
  3. Add spacing with `\phantom{}` for consistent widths
</Accordion>

<Accordion title="Matrix too wide for page">
  **Problem**: Large matrices extend beyond margins.

  **Solutions**:

  1. Use `\small` or `\footnotesize` before the matrix
  2. Use `bmatrix*}[r]` from `mathtools` for right-aligned entries
  3. Split into block matrices
  4. Consider using `array` environment with custom column spacing
</Accordion>

<Accordion title="Spacing between matrix elements">
  **Problem**: Elements too cramped or too spread out.

  **Solution**: Adjust array stretch:

  <LatexSource filename="example.tex" source={"\\renewcommand{\\arraystretch}{1.5} % 1.5x normal spacing\n\\begin{pmatrix}\na & b \\\\\nc & d\n\\end{pmatrix}"} />

  <RenderedOutput title="Expected effect">
    <Info>
      This code is a contextual or intentionally partial LaTeX excerpt, not a self-contained compilable document. Its visible result depends on the surrounding document, so the documentation shows the expected role without inventing a standalone preview.
    </Info>
  </RenderedOutput>
</Accordion>

## Best Practices

<Tip>
  **Matrix typesetting guidelines:**

  1. **Choose appropriate delimiters**: Use `vmatrix` for determinants, `pmatrix` for general matrices
  2. **Consistency**: Use the same notation style throughout your document
  3. **Size considerations**: Use `smallmatrix` for inline matrices
  4. **Alignment**: Right-align numbers in numeric matrices
  5. **Spacing**: Add `\,` or `\:` for better readability when needed
  6. **Block structure**: Use block matrices to show structure
  7. **Labels**: Add row/column labels when they aid understanding
</Tip>

## Package Recommendations

### Essential Packages

| Package      | Purpose                   | Key Features                   |
| ------------ | ------------------------- | ------------------------------ |
| `amsmath`    | Basic matrix environments | All standard matrix types      |
| `mathtools`  | Extended matrix features  | Starred versions, more options |
| `array`      | Custom column types       | Full control over layout       |
| `siunitx`    | Numeric alignment         | Decimal alignment in matrices  |
| `blkarray`   | Block arrays              | Labels and blocks              |
| `nicematrix` | Enhanced matrices         | Many advanced features         |

### Loading Order

<LatexSource filename="example.tex" source={"\\usepackage{amsmath}     % Load first\n\\usepackage{mathtools}   % Extends amsmath\n\\usepackage{array}       % For custom columns\n\\usepackage{siunitx}     % For numeric columns"} />

<RenderedOutput title="Expected effect">
  <Info>
    This is setup or structural LaTeX code. It changes available commands or document behavior, but it does not produce meaningful standalone page content by itself.
  </Info>
</RenderedOutput>

## Quick Reference Card

### Matrix Environments Summary

<LatexSource filename="example.tex" source={"% Basic environments (requires amsmath)\n\\begin{matrix}   ... \\end{matrix}     % no delimiters\n\\begin{pmatrix}  ... \\end{pmatrix}    % parentheses ( )\n\\begin{bmatrix}  ... \\end{bmatrix}    % brackets [ ]\n\\begin{Bmatrix}  ... \\end{Bmatrix}    % braces { }\n\\begin{vmatrix}  ... \\end{vmatrix}    % single bars | |\n\\begin{Vmatrix}  ... \\end{Vmatrix}    % double bars || ||\n\n% Small matrices (inline)\n\\begin{smallmatrix} ... \\end{smallmatrix}\n\n% Custom delimiters with array\n\\left[\\begin{array}{cc} ... \\end{array}\\right]"} />

<RenderedOutput title="Expected effect">
  <Info>
    This code is a contextual or intentionally partial LaTeX excerpt, not a self-contained compilable document. Its visible result depends on the surrounding document, so the documentation shows the expected role without inventing a standalone preview.
  </Info>
</RenderedOutput>

### Common Patterns

<LatexSource filename="example.tex" source={"% Identity matrix\n\\begin{pmatrix}\n1 & 0 & 0 \\\\\n0 & 1 & 0 \\\\\n0 & 0 & 1\n\\end{pmatrix}\n\n% General element notation\n\\begin{pmatrix}\na_{11} & \\cdots & a_{1n} \\\\\n\\vdots & \\ddots & \\vdots \\\\\na_{m1} & \\cdots & a_{mn}\n\\end{pmatrix}\n\n% Augmented matrix\n\\left[\\begin{array}{cc|c}\na & b & e \\\\\nc & d & f\n\\end{array}\\right]\n\n% Block matrix\n\\begin{pmatrix}\nA & B \\\\\nC & D\n\\end{pmatrix}"} />

<RenderedOutput title="Expected effect">
  <Info>
    This code is a contextual or intentionally partial LaTeX excerpt, not a self-contained compilable document. Its visible result depends on the surrounding document, so the documentation shows the expected role without inventing a standalone preview.
  </Info>
</RenderedOutput>

## Practice in LaTeX Cloud Studio

<CardGroup cols={2}>
  <Card title="Try matrices in the editor" icon="cloud" href="https://app.latex-cloud-studio.com/?utm_source=resources&utm_medium=card&utm_campaign=docs_open_app&utm_content=matrices_open_app">
    Test `pmatrix`, `bmatrix`, and augmented matrices in a live document and inspect the rendered output directly.
  </Card>

  <Card title="Tables vs matrices" icon="table-cells" href="/learn/latex/tables/creating-tables?utm_source=resources&utm_medium=related_guide&utm_campaign=docs_open_app&utm_content=matrices_tables_guide">
    Jump here when you need structured data layout rather than mathematical notation.
  </Card>
</CardGroup>

***

## Related Topics

<CardGroup cols={2}>
  <Card title="Subscripts & Superscripts" icon="subscript" href="/learn/latex/mathematics/subscripts-superscripts">
    Matrix element notation with indices
  </Card>

  <Card title="Mathematical Equations" icon="equals" href="/learn/latex/mathematics/equations">
    Multi-line equations and alignment
  </Card>

  <Card title="LaTeX Symbols Reference" icon="list" href="/learn/reference/symbols">
    Greek letters and math operators
  </Card>

  <Card title="Advanced Mathematics" icon="square-root-variable" href="/learn/latex/mathematics/advanced-math">
    Complex mathematical notation
  </Card>
</CardGroup>

## Further Reading & References

For authoritative documentation on LaTeX matrix environments and mathematical typesetting:

* **amsmath Package Documentation** - The standard package providing all matrix environments (pmatrix, bmatrix, vmatrix)
* **mathtools Package** - Extended features for matrices including starred versions and additional options
* **The LaTeX Companion (3rd Edition)** - Comprehensive reference for mathematical typesetting best practices
* **Linear Algebra Done Right** by Sheldon Axler - Standard textbook demonstrating matrix notation conventions

<Info>
  **Next steps**:

  * Learn about [Creating figures and images](/learn/latex/figures/inserting-images)
  * Explore [Advanced mathematics](/learn/latex/mathematics/advanced-math)
  * Master [Table creation](/learn/latex/tables/creating-tables) for data presentation
</Info>

<Tip>
  **LaTeX Cloud Studio** tip: Use our real-time preview feature to instantly see how your matrices render. No compilation wait time needed!
</Tip>
