Language Reference


SHAPE Function

SHAPE (matrix, nrow <, ncol> <, pad-value> );

The SHAPE function reshapes and repeats values in a matrix.

The arguments to the SHAPE function are as follows:

matrix

is a numeric or character matrix or literal.

nrow

specifies the number of rows for the new matrix.

ncol

specifies the number of columns for the new matrix.

pad-value

specifies a value to use for elements of the new matrix if the quantity nrow$\times $ncol is greater than the number of elements in matrix.

The SHAPE function creates a new matrix from data in matrix. The values nrow and ncol specify the number of rows and columns, respectively, in the new matrix. The function can reshape both numeric and character matrices.

There are three ways of using the function:

  • If only nrow is specified, the number of columns is determined as the number of elements in the object matrix divided by nrow. The number of elements must be exactly divisible; otherwise, a conformability error occurs.

  • If both nrow and ncol are specified, but not pad-value, the result is achieved by moving along the rows until the desired number of elements is obtained. The operation cycles back to the beginning of the object matrix to get more elements, if needed.

  • If pad-value is specified, the operation first copies the elements of matrix into the result. If the number of elements in the result matrix is larger than the number of elements in matrix, the pad-value value is used for the remaining elements.

If nrow or ncol is specified as 0, then the number of rows or columns, respectively, becomes the number of values divided by ncol or nrow.

For example, the following statements create constant matrices of a given size:

r = shape(12, 3, 4);       /* 3 x 4 matrix with constant value 12 */
s = shape({99 31}, 3, 3);  /* 3 x 3 matrix with alternating values */
print r, s;

Figure 25.374: Constant and Repeated Matrices

r
12 12 12 12
12 12 12 12
12 12 12 12

s
99 31 99
31 99 31
99 31 99



The SHAPE function produces the result matrix by traversing the argument matrix in row-major order until the specified number of elements is reached. If necessary, the SHAPE function reuses elements.

You can also use the SHAPE function to reshape an existing matrix, as shown in the following statements:

t = shape(1:6, 2);
print t;

Figure 25.375: Reshaped Matrix

t
1 2 3
4 5 6