Search code examples
pythonnumpyoptimizationcvxoptcvxpy

How to convert a CVXPY result into numpy


I have got an optimization problem defined in cvxpy, but want to work with the result in my code in numpy afterwards - how can I convert it from cvxpy into numpy?

It is of type

<class 'numpy.matrixlib.defmatrix.matrix'>

If I want to plot it to see the result, matplotlib shows only a blue area.


Solution

  • https://docs.scipy.org/doc/numpy/reference/generated/numpy.matrix.view.html seems to have all you need

    numpy's view can be used (afaik) in any which way you can use numpy's array directly.

    It makes sense to "convert" to a numpy array if you want to get a copy of data:

    y
    matrix([[1, 0, 0, 0, 2, 0, 0, 0],
            [3, 0, 0, 0, 4, 0, 0, 0]], dtype=int16)
    
    type(y)
    numpy.matrixlib.defmatrix.matrix    
    
    
    n = numpy.array(y)
    n[1,2] = 999
    
    n
    array([[  1,   0,   0,   0,   2,   0,   0,   0],
           [  3,   0, 999,   0,   4,   0,   0,   0]], dtype=int16)
    
    y
    matrix([[1, 0, 0, 0, 2, 0, 0, 0],
            [3, 0, 0, 0, 4, 0, 0, 0]], dtype=int16)