# Creating a matrix with a formula or function: makemat matrix

### 5.44.4 Creating a matrix with a formula or function: makemat matrix

You can use a function or a formula to specify the elements of a matrix with the makemat or matrix command.

- makemat takes three arguments:
  - f, a function of two variables j and k which returns the value of aj,k, the element at row index j and column index k of the resulting matrix.
  - n and p, two positive integers.
- makemat(f,n,p) returns the n× p matrix A=(aj,k) with aj,k=f(j,k) for j=1..n and k=1..p.

#### Example.

Input:

makemat((j,k)->j+k,4,3)

or:

h(j,k):=j+k
makemat(h,4,3)

Output:

⎛
⎜
⎜
⎜
⎝

0 | 1 | 2
1 | 2 | 3
2 | 3 | 4
3 | 4 | 5

⎞
⎟
⎟
⎟
⎠

Note that the indices are counted starting from 0.

The matrix command can be used similarly, but note that the arguments are given in a different order and the indices start at 1.
(matrix can also be used to turn tables into matrices; see Section 5.46.1.)

- matrix takes two mandatory arguments and one optional argument:
  - n and p, two integers.
  - Optionally, f, a function of two variables j and k which should return the value of aj,k, the element at row index j and column index k of the resulting matrix.
- matrix(n,p) returns the n× p matrix consisting of all 0s.
- matrix(n,p,f) returns the n× p matrix A=(aj,k) with aj,k=f(j,k) for j=1..n and k=1..p.

#### Examples.

- Input:
  matrix(2,3)
  Output:

  ⎛
  ⎜
  ⎝

  0 | 0 | 0
  0 | 0 | 0

  ⎞
  ⎟
  ⎠

- Input:
  matrix(4,3,(j,k)->j+k)
  or:

  h(j,k):=j+k
  matrix(4,3,h)

  Output:

  ⎛
  ⎜
  ⎜
  ⎜
  ⎝

  0 | 1 | 2
  1 | 2 | 3
  2 | 3 | 4
  3 | 4 | 5

  ⎞
  ⎟
  ⎟
  ⎟
  ⎠