Skip to content

FAQ: What is the difference between an Opti.variable and casadi.MX.sym? Can I mix the two?

András Retzler edited this page Oct 21, 2022 · 4 revisions

An Opti.variable˛is indeed like an MX.sym, but with special bookkeeping so that Opti knows that it's a decision variable to optimize. If you are using Opti, you shall not add an MX.sym to your problem, because you will get an error message:

Error using casadi.Opti/minimize (line 119)
Error in Opti::minimize [OptiNode] at .../casadi/core/optistack.cpp:88:
.../casadi/core/optistack_internal.cpp:506: Unknown: MX symbol 'y' of shape 1x1, declared outside of Opti.
Note: you cannot use a raw MX.sym in your Opti problem, only if you package it in a CasADi Function.

This is because Opti doesn't know what that symbol is for, is it a decision variable?

Another difference for Opti.variable items that their name inside the expressions is always like: opti_<# instance>_x_<# variable>, for example:

>> opti1 = casadi.Opti()
opti = 

Opti {
  instance #1
  #variables: 0 (nx = 0)
  #parameters: 0 (np = 0)
  #constraints: 0 (ng = 0)
  CasADi solver needs updating.
}

>> opti2 = casadi.Opti()

opti = 

Opti {
  instance #2
  #variables: 0 (nx = 0)
  #parameters: 0 (np = 0)
  #constraints: 0 (ng = 0)
  CasADi solver needs updating.
}
>> a=opti2.variable()

a = 

opti2_x_1
>> b=opti2.variable()

b = 

opti2_x_2

(In most cases, you would only have one Opti instance though.)

Indeed, combining opti.variable-s will result in an MX expression:

>> class(a+b)

ans =

    'casadi.MX'
Clone this wiki locally