casadi.reshape not compatible with numpy.reshape

663 views
Skip to first unread message

harzer...@gmail.com

unread,
Jun 15, 2021, 11:26:34 AM6/15/21
to CasADi
Hi,

during my work I ran into some issue (that are now solved) that were due to the different behavior of casadi.reshape() and numpy.reshape(). As in the example, I tried to reshape a matrix into a vector It looks like casadi shapes columns first and numpy rows first.

Sample Code
import casadi as ca
import numpy as np

A = ca.MX.sym('A',(2,2))
casadiReshape = ca.Function('
caRes',[A],[A.reshape((4,1))])
print(f"Matrix: {np.array([[1, 2],[3, 4]])}")
print(f"Casadi: {casadiReshape(np.array([[1, 2],[3, 4]]))}")
print(f"Numpy: {np.array([[1, 2],[3, 4]]).reshape((4,1))}")


Prints:
Matrix: [[1 2]
              [3 4]]
Casadi:  [1, 3, 2, 4]
Numpy: [[1]
 [2]
 [3]
 [4]]

Its not an issue any more, I just wanted to ask if this is intended?

Cheers Jakob




Kirill Klimov

unread,
Jun 16, 2021, 7:49:38 AM6/16/21
to CasADi
Hi! I'm not a CasADi dev, but as far as i know it's intended. NumPy uses row major data storage but CasADi uses column major storage. Natural way to implement fast reshape is to reshape matrix without reordering data. 
Also, probably CasADi  behavior consistent with matlab.

вторник, 15 июня 2021 г. в 18:26:34 UTC+3, harzer...@gmail.com:

Joel Andersson

unread,
Jun 16, 2021, 10:36:33 AM6/16/21
to CasADi
Kirill's answer is correct. CasADi uses column major storage, like MATLAB or Fortran. Numpy can actually use either row-major or column major storage, but the default is row-major. You should be able to get column-major by setting the "order" parameter to "F":

numpy.reshape(anewshapeorder='F')

Joel


Reply all
Reply to author
Forward
0 new messages