In Python I can reshape array remaining one dimension unknown, allowing Python to infer it automatically:

np.reshape(A, (2,-1))
array([[1, 2, 3],
       [4, 5, 6]])

Is the same possible in Mathematica?


In Python I can set any dimension to -1, not only last, for example

A = np.array(range(3*4*5))
np.reshape(A, (3, -1, 5))

apparently, reshape function calculates product of explicit dimensions and divides total length by it to compute unknown dimension. In Mathematica I can do this explicitly

A = Range[3*4*5]
ArrayReshape[A, {3, Length[A]/3/5, 5}] 

but can I do as in Python?

EDIT: I reckon a better way to pose this question is to ask:

How can I implement similar functionality in Mathematica, preferably in a general way?

  • 4
    $\begingroup$ Use Partition. $\endgroup$
    – Alan
    Oct 18, 2017 at 22:33
  • $\begingroup$ To elaborate on @Alan's comment, a = Range[6]; Partition[a, 3] will give you your output. Partition also has a lot of arguments you can play around with to generate more complex lists from your input. $\endgroup$ Oct 19, 2017 at 0:46
  • $\begingroup$ @Alan can I do all other things with Partition? $\endgroup$
    – Dims
    Oct 19, 2017 at 11:05
  • 2
    $\begingroup$ No, to have a function of equal generality you must implement it yourself. $\endgroup$
    – Szabolcs
    Oct 19, 2017 at 12:25


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Browse other questions tagged or ask your own question.