median overloads median operator
m = median(X)
The following silly example defines a regression problem with the constraint that the mean and the median of the decision variable are equal. As usual, we add explicit bound constraints to improve the big-M reformulations.
A = randn(20,5); b = randn(20,1)*20; x = sdpvar(5,1); e = b-A*x; F = [mean(x) == median(x), -100 <= x <= 100]; optimize(F,norm(e,1));
Since median is implemented using a mixed-integer model using a big-M approach, it is crucial that all involved variables have explicit bound constraints.
median builds on the sort operator which is extremely expensive. Sorting a variable of with \(n\) elements requires \(n^2\) binary variables. A more efficient integer model can be developed, make a feature request if your need this.