Skip to content

Instantly share code, notes, and snippets.

@johanlofberg
Created May 2, 2021 06:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save johanlofberg/9a40149e21e5fa0266970cf2d75c6027 to your computer and use it in GitHub Desktop.
Save johanlofberg/9a40149e21e5fa0266970cf2d75c6027 to your computer and use it in GitHub Desktop.
%% Setup
n = 20;
x = sdpvar(n,1);
y = randn(n,1);
Objective = (x-y)'*(x-y);
%% Manual implies
d = binvar(n,1)
M = 1;
Model = [x >= -(1-d)*M, sum(d) >= 0.5*n, -1 <= x <= 1];
optimize(Model,Objective)
%% Built-in implies
Model = [implies(d,x>=0), sum(d) >= 0.5*n, -1 <= x <= 1];
optimize(Model,Objective)
%% Sort
sorted = sort(x);
Model = [sorted(n/2:end) >= 0, -1 <= x <= 1];
optimize(Model,Objective)
%% Median
Model = [median(x) >= 0, -1 <= x <= 1];
optimize(Model,Objective)
%% Sign
Model = [sum(sign(x)) >= 0, -1 <= x <= 1];
optimize(Model,Objective)
%% Nnz
Model = [nnz(x >= 0) >= n/2, -1 <= x <= 1];
optimize(Model,Objective)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment