# Rectangular: Three Different Sizes

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

Square matrices hide a trap: every dimension is 16, so any loop bound "works".
Real matmuls are rectangular — here `rectA` is 8×32 (8 rows, 32 columns) and
`rectB` is 32×12, so the product is **8×12**. Suddenly there are
three different sizes and each belongs somewhere specific.

Two of them shape the launch: `output: [width, height]` = [columns of B,
rows of A] = `[12, 8]` — already set up below. The third, 32, is the
**shared dimension**: A's columns must equal B's rows, and that's the only
dimension the loop is allowed to run over.

## Figures

- **8 and 12 shape the launch; 32 is the loop’s whole world**

## Goal

**Goal:** compute the 8×12 product `rectA × rectB` — fix the
inner loop so it covers the full shared dimension of 32.

## Requirements

- Keep `output: [12, 8]` — columns of B across, rows of A down
- Loop `k` over the *shared* dimension: all 32 of it
- Sum `a[this.thread.y][k] * b[k][this.thread.x]` as before

## Hint 1 — which size does the loop get?

The loop walks *across* a row of A (32 long) and *down* a column
of B (also 32 long — that's why the shapes are compatible). Neither 8 nor 12 appears
in the loop at all.

## Hint 2 — the fix

The starter loop stops at 12 — it sums only the first 12 of 32 terms. Change
the bound: `for (let k = 0; k < 32; k++)`.

## Same idea elsewhere

BLAS calls this M, N, K — `sgemm(M, N, K, …)` in cuBLAS and rocBLAS
keeps the three sizes as separate parameters for exactly this reason. Mixing them up is
the classic GEMM bug on every platform, not just here.

## Starter code

```js
// (8×32) times (32×12) → 8×12. Three sizes, three different jobs.
const gpu = new GPU({ mode });

const multiply = gpu.createKernel(function (a, b) {
  let sum = 0;
  // TODO: this loop stops too early — it covers 12 of the 32
  // shared elements. Which of the three sizes does the loop own?
  for (let k = 0; k < 12; k++) {
    sum += a[this.thread.y][k] * b[k][this.thread.x];
  }
  return sum;
}, {
  // [width, height] = [columns of B, rows of A]
  output: [12, 8],
});

const c = await multiply(rectA, rectB);
console.log('rows:', c.length, 'cols:', c[0].length);
```

---

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

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