flatten

Syntax

flatten(X)

Arguments

X is a vector, tuple or matrix.

Details

Convert X into a 1D vector.

Note that for a tuple:

  • If it contains tuple elements, flatten converts these elements to 1D vectors and retains other elements, returns a tuple.

  • If it does not contain tuple elements, flatten returns a 1D vector.

Examples

Convert a matrix into a vector.

m=1..10$5:2;
flatten(m);
// output: [1,2,3,4,5,6,7,8,9,10]

Convert a list of vectors into a vector.

a=1..10;
b = a cut 2;
b;
// output: ([1,2],[3,4],[5,6],[7,8],[9,10])

flatten(b);
// output: [1,2,3,4,5,6,7,8,9,10]

x=flatten([1, [2,3]]);
x;
// output: [1,2,3]

Convert a tuple with tuple elements into a 1d vector, which involves several times of flatten operations:

list = (1, (2, (3, 4, 5)), (6, 7), 8, [9])
x1 = flatten(list)
x1
//(3, 4, 5) and (6, 7) are converted to 1D vectors
// output:(1,(2,[3,4,5]),[6,7],8,[9])

x2= flatten(x1)
x2
//(2,[3,4,5]) is converted to 1D vectors
// output:(1,[2,3,4,5],[6,7],8,[9])

x3= flatten(x2)
x3
// flatten to 1D vector
// output:[1,2,3,4,5,6,7,8,9]

Or use flatten with reduce to get the result after iteration:

reduce(flatten, init=list)
// output:[1,2,3,4,5,6,7,8,9]