Skip to content

Minimizing a 6 dimensional problem with 3 constraints in python

An answer to this question on Stack Overflow.

Question

We are given a problem that required the minimization of the cost of food for a student.She has to have calories (2,000 kcal), protein (55 g), and calcium (800 mg). and there are six types of food in total. We have to do this problem with the Python CVXPY package. Here are my code, but it is returning the ValueError: Cannot broadcast dimensions (3,) (3, 1)error. Here is the code of my matrix.

A=np.array([[110,205,160,160,420,260],[4,32,13,8,4,14],[2,12,54,285,22,80]) 
//Note:A is the matrix with the contents of all the foods//
b=np.array([[2000,55,800]])
//Note: b represents the desired value for calories, protein and calcium.//
c=np.array([[3,24,13,9,20,19]])
//Note c represents the price of the 6 types of food. //

There was an additional criterion that was added where a max serving of each type of food was required. and my code for that looked like:

d= np.array([[4,3,2,8,2,2]])
x_vec = cp.Variable(6)
//where d represented the max serving constraints on each of the six types of foods.//

Lastly, I have to code for the minimizing and problem-solving, which for some reason just doesn't seem to work

matrix_prob = cp.Problem(cp.Minimize(cp.sum(c.T @ x_vec)),
                        constraints=[A@x_vec <= b, x_vec <= d])
//Note:here I minize the sum of matrix c while considering the constraints of b and d.//
matrix_solution = matrix_prob.solve()
print('Optimal value (matrix form):    {:.4f}'.format(matrix_solution))

Answer

The error:

ValueError: Cannot broadcast dimensions  (3,) (3, 1)

speaks for itself: you're trying to do an operation involving a one-dimensional and a two-dimensional object. Since the 2d object has length 1 in its second dimension, this suggests that dropping that dimension will solve your problem.

Therefore, try making b, c, and d one-dimensional arrays, e.g.:

d = np.array([4,3,2,8,2,2])

Also: Python uses # for comments. I'm not sure why you've used //, but don't.