Reshape vector of odd length to multi-dimensional array

Hi,

I’m trying to reshape a vector of odd length (15) into a multi-dimensional array and getting a DimensionMismatch("array size 15 must be divisible by the product of the new dimensions (2, Colon())") error, which makes sense but I don’t know the workaround this. Numpy automatically takes care of this

Here’s the code:
Julia

A = Vector(1:15)
reshape(A, 2, :) # throws an error

Python

import numpy as np
A = [i for i in range(1, 16)]
np.array(A, ndmin=2)

Please assist. Thanks

How does it take care of this?

1 Like
>>> import numpy as np
>>> A = [i for i in range(1, 16)]
>>> np.array(A, ndmin=2)
array([[ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15]])

ndmin int, optional
Specifies the minimum number of dimensions that the resulting array should have. Ones will be pre-pended to the shape as needed to meet this requirement.

Does this do what you’re looking for?

julia> reshape(Vector(1:15), 1, :)
1×15 Matrix{Int64}:
 1  2  3  4  5  6  7  8  9  10  11  12  13  14  15
3 Likes

What might be the idea here (vs. zero, ±Inf or NaN)?

The wording is a bit confusing - ones are not prepended to the array, but rather to its shape:

>>> np.shape(A)
(15,)
>>> np.array(A, ndmin=2).shape
(1, 15)
2 Likes

Yep, and np.array(range(1, 17), ndmin=2).shape is (1, 16), so that function does not try to make a shape of (2, X) even when it’s possible, it’s just not what ndmin means.

There is a Python equivalent of reshape(1:16, 2, :). np.reshape(range(1, 17), (2, -1)) does make a shape of (2, 8), where -1 can specify (only) one dimension of unknown length. Either way, 1:15/range(1, 16) will throw an error because (2, 7.5) isn’t a valid shape.

1 Like

Thanks! The wording, especially ndim, was confusing me.