reshape

reshape(A, dims)

Create an array with the same data as the given array, but with different dimensions. An implementation for a particular type of array may choose whether the data is copied or shared.

Examples

  1. Reshape a 1-dimensional array:

    julia> arr = [1, 2, 3, 4, 5, 6];
    julia> reshape(arr, (2, 3))
    2×3 Matrix{Int64}:
    1  3  5
    2  4  6

    This example reshapes the 1-dimensional array arr into a 2x3 matrix.

  2. Reshape a multi-dimensional array:

    julia> matrix = [1 2 3; 4 5 6; 7 8 9; 10 11 12];
    julia> reshape(matrix, (2, 6))
    2×6 Matrix{Int64}:
    1  3  5  7   9  11
    2  4  6  8  10  12

    It reshapes the 2x3 matrix matrix into a 2x6 matrix.

  3. Change the shape of a vector:
    julia> vec = [1, 2, 3, 4, 5, 6];
    julia> reshape(vec, (2, 3))
    2×3 Matrix{Int64}:
    1  3  5
    2  4  6

    This example reshapes the vector vec into a 2x3 matrix.

Common mistake example:

julia> arr = [1, 2, 3, 4, 5, 6];
julia> reshape(arr, (2, 4))
ERROR: DimensionMismatch("new dimensions (2, 4) must be consistent with array size 6")

In this example, the desired dimensions (2, 4) are not consistent with the size of the array arr. It's important to ensure that the total number of elements remains the same after reshaping.

See Also

Array, broadcast, cat, combinations, conj!, digits!, fieldnames, fill, fill!, last, length, maximum, minimum, ones, parent, parentindexes, partitions, permutations, pointer, pointer_to_array, promote_shape, rand!, reshape, scale, similar, sum, sum_kbn, takebuf_array, transpose!, vec, zeros,

User Contributed Notes

Add a Note

The format of note supported is markdown, use triple backtick to start and end a code block.

*Required Field
Details

Checking you are not a robot: