1

I am using cvxpy to solve an optimization problem. I want to store the output, a matrix into a ndarray.

This is the reduced test case. a representing the returned value from cvxpy.

import numpy as np

z = np.zeros((3,7))
a = np.matrix("[1; 2; 3]")
z[0, 0] = a[0]
z[1, 0] = a[1]
z[2, 0] = a[2]

I would like to replace the last three lines with something better, but everything I try results in an error. E.g.,

>>> z[:, 0] = a
Traceback (most recent call last):
  File "<input>", line 1, in <module>
ValueError: could not broadcast input array from shape (3,1) into shape (3)
>>> np.copyto(z[:, 0], a)
Traceback (most recent call last):
  File "<input>", line 1, in <module>
ValueError: could not broadcast input array from shape (3,1) into shape (3)

I would appreciate a little help. Thank you.

1 Answer 1

1

One simple way would be to use a list of the column index for indexing into z and then simply assign the NumPy matrix a there -

z[:,[0]] = a

Another way would be to use the transpose of the matrix a, which would be a row vector to assign into the sliced version of the first column in z -

z[:,0] = a.T
Sign up to request clarification or add additional context in comments.

3 Comments

a.A1 might work here. I.e. convert the 2d matrix into a 1d array.
@hpaulj You love that .A1 thing, don't you? :)
@hpaulj I didn't know about a.A1, such a nice syntactic sugar :P

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.