Creating a matrix with a formula or function

### 14.2.4 Creating a matrix with a formula or function

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=[ajk] with ajk=f(j,k) for j=1…,n and k=1,…,p.

The matrix command can be used similarly, but note that the arguments are given in a different order and the indices start at 1. (See Section 14.4.2 for other uses of matrix.)

- 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 zeros.
- matrix(n,p,f) returns the n× p matrix A=[ajk] with ajk=f(j,k) for j=1,…,n and k=1,…,p.

#### Examples

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

or:

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

⎡ ⎢ ⎢ ⎢ ⎣ |
0 | 1 | 2
1 | 2 | 3
2 | 3 | 4
3 | 4 | 5
| ⎤ ⎥ ⎥ ⎥ ⎦

Note that the indices are counted starting from 0.

matrix(2,3)

⎡ ⎢ ⎣ |
0 | 0 | 0
0 | 0 | 0
| ⎤ ⎥ ⎦

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

or:

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

⎡ ⎢ ⎢ ⎢ ⎣ |
0 | 1 | 2
1 | 2 | 3
2 | 3 | 4
3 | 4 | 5
| ⎤ ⎥ ⎥ ⎥ ⎦