# The Full Grid: Matrix × Matrix

*Task 2 of 5 · [Matrix Multiply](https://gpu.rocks/learn/matrix-multiply-972e080b.md) · GPU.js Learn*

On the CPU, `C = A × B` is the classic triple loop: over rows, over
columns, over `k`. On the GPU the outer two loops **vanish into the
launch** — `output: [16, 16]` starts 256 threads, one per cell of
`C`, and only the innermost loop survives inside the kernel.

Cell `C[y][x]` is the dot product of **row y of A** with
**column x of B**: walk `k` across the row
`a[y][k]` and down the column `b[k][x]`. Same loop as task 1 —
now every thread aims it at its own row/column pair.

## Figures

- **row y across, column x down — 256 threads, each owning one dot product**

## Goal

**Goal:** compute the 16×16 product `matA × matB` — each
thread returns the dot product of its row of `a` with its column of
`b`.

## Requirements

- Keep `output: [16, 16]` — one thread per cell of C
- Loop `k` over the 16 shared elements
- Accumulate `a[this.thread.y][k] * b[k][this.thread.x]` and return the sum

## Hint 1 — row and column

`this.thread.y` picks the row of `a`,
`this.thread.x` picks the column of `b`, and `k` is
the only index that moves during the loop.

## Hint 2 — the inner loop

```js
let sum = 0;
for (let k = 0; k < 16; k++) {
  sum += a[this.thread.y][k] * b[k][this.thread.x];
}
return sum;
```

## Same idea elsewhere

This one-thread-per-output-cell matmul is the "naive kernel" every WebGPU and
CUDA tutorial starts from — and the baseline that tiled, shared-memory versions are
measured against. The structure you just wrote is their starting point too.

## Starter code

```js
// output: [16, 16] launches 256 threads — one per cell of C.
const gpu = new GPU({ mode });

const multiply = gpu.createKernel(function (a, b) {
  // TODO: this is the ELEMENTWISE product — one term, no loop.
  // C[y][x] needs the whole dot product: loop k over the 16
  // shared elements, walking a's row and b's column.
  return a[this.thread.y][this.thread.x] * b[this.thread.y][this.thread.x];
}, { output: [16, 16] });

const c = await multiply(matA, matB);
console.log('C[0][0] =', c[0][0]);
```

---

Interactive version: https://gpu.rocks/learn/matrix-multiply-972e080b/2

[Previous task](https://gpu.rocks/learn/matrix-multiply-972e080b/1.md) · [Next task](https://gpu.rocks/learn/matrix-multiply-972e080b/3.md)
