naginterfaces.library.rand.matrix_2waytable(mode, totr, totc, comm, statecomm)[source]

matrix_2waytable generates a random two-way table.

For full information please refer to the NAG Library document for g05pz


A code for selecting the operation to be performed by the function.

Set up reference vector only.

Generate two-way table using reference vector set up in a prior call to matrix_2waytable.

Set up reference vector and generate two-way table.

totrint, array-like, shape

The row totals, , for .

totcint, array-like, shape

The column totals, , for .

commdict, communication object, modified in place

Communication structure for the reference vector.

If , this argument must have been initialized by a prior call to matrix_2waytable.

statecommdict, RNG communication object, modified in place

RNG communication structure.

This argument must have been initialized by a prior call to init_repeat() or init_nonrepeat().

xNone or int, ndarray, shape

If or , a pseudorandom two-way table, , with element containing the th entry in the table such that and

(errno )

On entry, .

Constraint: , or .

(errno )

On entry, .

Constraint: .

(errno )

On entry, .

Constraint: .

(errno )

On entry, at least one element of is negative or sums to zero.

(errno )

On entry, has at least one negative element.

(errno )

or is not the same as when [‘r’] was set up in a previous call.

Previous value of and .

Previous value of and .

(errno )

On entry, [‘state’] vector has been corrupted or not initialized.

(errno )

On entry, the arrays and do not sum to the same total: array total is , array total is .


Given row totals and column totals (with , say), matrix_2waytable will generate a pseudorandom two-way table of integers such that the row and column totals are satisfied.

The method used is based on that described by Patefield (1981) which is most efficient when is large relative to the number of table entries (i.e., ). Entries are generated one row at a time and one entry at a time within a row. Each entry is generated using the conditional probability distribution for that entry given the entries in the previous rows and the previous entries in the same row.

A reference vector is used to store computed values that can be reused in the generation of new tables with the same row and column totals. matrix_2waytable can be called to simply set up the reference vector, or to generate a two-way table using a reference vector set up in a previous call, or it can combine both functions in a single call.

One of the initialization functions init_repeat() (for a repeatable sequence if computed sequentially) or init_nonrepeat() (for a non-repeatable sequence) must be called prior to the first call to matrix_2waytable.


Patefield, W M, 1981, An efficient method of generating tables with given row and column totals, Appl. Stats. (30), 91–97