4
$\begingroup$

I am trying to solve a simple maximization problem in Mathematica, using matrix and vector notation.

myVect = {{x}, {y}}
offDiag = {{0, 1}, {1, 0}}
Maximize[{0.5*Transpose[myVect].offDiag.myVect, 
  Transpose[myVect].{{2}, {2}} - 1 == 0}, {myVect}]

So I'm just trying to maximize the area of a rectangle with the circumference of 1, using this notation (I'll need it for more complex problems later). However, I get this error message:

Maximize::ivar: {{x},{y}} is not a valid variable. >>

Both the objective function and the equality constraint by themselves seem to work. What am I doing wrong? Is this a syntax error?

$\endgroup$
3
$\begingroup$

There are three problems with your posted code.

  1. Your objective function is a 1x1 matrix rather than a scalar.
  2. Your constraint equation is malformed. One side is a 1x1 matrix, the other is a scalar. They should both be scalars.
  3. The variables should be in a flat list.

@Willinski already gave a more natural way of expressing vectors in Mathematica, so that the . acts like contraction (returning a scalar) rather than matrix multiplication (returning a 1x1 matrix). It works because Mathematica automatically interprets a List as a 1xn or nx1 matrix depending on the context.

In case you really need to keep your matrix notation for myVect (possibly for some kind of generalization), then you need to make sure the objective function and constraint equation are scalars. For the posted code, you can achieve this by using Part. The variables have to be a flat list, so I flattened it and then used an anonymous function to reconstruct the formatted version of the results.

myVect = {{x}, {y}}
offDiag = {{0, 1}, {1, 0}}
Maximize[{
 (0.5*Transpose[myVect].offDiag.myVect)[[1, 1]],
 ({{x, y}}.{{2}, {2}})[[1, 1]] - 1 == 0
 }, Flatten@myVect] //
 {#[[1]], myVect -> (myVect /. #[[2]])} &
$\endgroup$
8
$\begingroup$

Your corrected code:

myVect = {x, y};
offDiag = {{0, 1}, {1, 0}};
Maximize[1/2*myVect.offDiag.myVect, myVect.{2, 2} - 1 == 0, myVect]

{1/16, {x -> 1/4, y -> 1/4}}
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.