Forum Discussion
VMelgarejoCaz
Jan 20, 2025Copper Contributor
Transpose in arrays of n columns
Hello all and thanks in adhance for your help. I am tryting to find a formula or shortcut that would allow me to transpose arrays of n columns into matrixes of n rows and n columns, to plot the d...
Patrick2788
Jan 22, 2025Silver Contributor
This solution is from a past discussion concerning Thunks.
=ReShapeMatrixλ(data, 3, 3)
ReShapeMatrixλ gets an assist from Peter's EVALTHUNKARRλ -
//Re-shape a matrix by specifying width and depth. 'shape' - 0 to vertically stack arrays,
//1 to horizontally stack arrays. 'shape' defaults to vertical stack if omitted.
//'pad_with' defaults to "" if omitted.
ReShapeMatrixλ = LAMBDA(matrix, depth, width, [shape], [pad_with],
LET(
//Prevent uneven distribution of rows and/or columns by
//ensuring dimensions are properly rounded according to
//depth and width.
i, CEILING.MATH(ROWS(matrix), depth),
j, CEILING.MATH(COLUMNS(matrix), width),
//Set padding and expand matrix as needed.
padding, IF(ISOMITTED(pad_with), "", pad_with),
M, EXPAND(matrix, i, j, padding),
//Create two matrices which serve as row and column coordinates
//for INDEX.
M_rows, SEQUENCE(i / depth, , , depth) * SEQUENCE(, j / width, , 0),
M_cols, SEQUENCE(, j / width, , width) * SEQUENCE(i / depth, , , 0),
//Generate 'r' and 'c' coordinates based on starting row (v₁) and column (v₂).
//Retrieve 'block' from matrix as a vector and stuff in a thunk.
CreateVectors, LAMBDA(v₁, v₂,
LET(
r, TOCOL(SEQUENCE(depth, , v₁) * SEQUENCE(, width, , 0)),
c, TOCOL(SEQUENCE(, width, v₂) * SEQUENCE(depth, , , 0)),
block, INDEX(M, r, c),
THUNK(block)
)
),
//Map and convert to vector to prepare for unpacking.
thunks, TOCOL(MAP(M_rows, M_cols, CreateVectors)),
//Unpack thunks.
unpacked, EVALTHUNKARRλ(thunks),
//Wrap vector according to desired shape.
vshaped, WRAPROWS(unpacked, depth * width),
hshaped, WRAPCOLS(unpacked, depth * width),
reshaped, IF(
ISOMITTED(shape),
vshaped,
IF(shape, hshaped, vshaped)
),
reshaped
)
);