FAQ: How to transform a Casadi matrix to a Numpy array - casadi/casadi GitHub Wiki
From CasADi.DM to numpy
TL;DR you can do np.array(my_casadi_DM_object)
.
An example:
import casadi as cs
import numpy as np
casadi_array = cs.DM([1,2,3,4,5])
numpy_array_1 = np.array(casadi_array)
print(numpy_array_1)
print()
numpy_array_2 = np.array(casadi_array).squeeze()
print(numpy_array_2)
Numpy distinguishes between 0D, 1D, and 2D arrays. np.array on a Casadi matrix always gives a 2D numpy array. Calling squeeze()
removes the unit dimension.
If you want to access the first element without squeeze call:
numpy_array_1[0][0]
With squeeze
it is:
numpy_array_2[0]
Note: first you need to make sure that the matrix is fully numeric, not symbolic. Use for example full
, evalf
, substitute
to make it numeric.