SHAPE Function |
The SHAPE function reshapes and repeats values in a matrix. The arguments are as follows:
is a numeric or character matrix or literal.
specifies the number of rows fo the new matrix.
specifies the number of columns for the new matrix.
specifies a value to use for elements of the new matrix if the quantity nrowncol 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 is diagnosed.
If both nrow and ncol are specified, but not pad-value, the result is obtained 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 moves the elements of the object matrix first and then fills in any extra positions in the result with the pad-value.
If nrow or ncol is specified as 0, 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;
r | |||
---|---|---|---|
12 | 12 | 12 | 12 |
12 | 12 | 12 | 12 |
12 | 12 | 12 | 12 |
s | ||
---|---|---|
99 | 31 | 99 |
31 | 99 | 31 |
99 | 31 | 99 |
Notice that 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;
t | ||
---|---|---|
1 | 2 | 3 |
4 | 5 | 6 |