Skip to content

Instantly share code, notes, and snippets.

View johanlofberg's full-sized avatar

Johan Löfberg johanlofberg

View GitHub Profile
n = 6;
th = linspace(-pi, pi, 2*n+1);
xi = (1+rem((1:2*n+1),2)).*cos(th);
yi = (1+rem((1:2*n+1),2)).*sin(th);
clf;
hold on;
grid on
plot( xi, yi, 'b*-' );
axis equal;
%% Basic model
Nunits = 3;
Horizon = 48;
Pmax = [100;50;25];
Pmin = [20;40;1];
Q = diag([.04 .01 .02]);
C = [10 20 20];
Pforecast = 100 + 50*sin((1:Horizon)*2*pi/24);
onoff = binvar(Nunits,Horizon,'full');
%% MILP model
n = 4;
m = 10;
p = randn(m,1);
R = randn(m,n);
w0 = randn(n,1);
w = sdpvar(n,1);
objective = sort(R*w,'descend')'*p+norm(w-w0,1);
Model = [norm(w,inf)<=1];
%% 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];
%% Setup
n = 10;
x = randn(2,n);
s = sdpvar(n,1);
z = sdpvar(2,1);
% Define and plot convex hull of points
clf;
plot([z == x*s, s>=0, sum(s)==1],z);hold on
plot(x(1,:),x(2,:),'k*');
% Data
x0 = -1
x1 = 0;
x2 = 1;
y0 = 0;
y1 = 1;
y2 = 0;
n = 9;
% Solve conditions
%% Always start by clearing the internals
yalmip('clear')
% Define variables
x = sdpvar(10,1);
% Define constraints
Constraints = [sum(x) <= 10, x(1) == 0, 0.5 <= x(2) <= 1.5];
for i = 1 : 7
Constraints = [Constraints, x(i) + x(i+1) <= x(i+2) + x(i+3)];
%% Generate data
blues = randn(2,25);
greens = randn(2,25)+2;
plot(greens(1,:),greens(2,:),'g*')
hold on
plot(blues(1,:),blues(2,:),'b*')
%% Define and solve model
a = sdpvar(2,1);
b = sdpvar(1);
x = [1 2 3 4 5 6]';
t = (0:0.02:2*pi)';
Atrue = [sin(t) sin(2*t) sin(3*t) sin(4*t) sin(5*t) sin(6*t)];
ytrue = Atrue*x;
A = Atrue;%.*(0.5+rand(315,6));
A(100:210,:)=.1;
y = Atrue*x+randn(length(ytrue),1);
%% Low-level
xhat = sdpvar(6,1);
%% Create data
x = [1 2 3 4 5 6]';
t = (0:0.02:2*pi)';
A = [sin(t) sin(2*t) sin(3*t) sin(4*t) sin(5*t) sin(6*t)];
e = (-4+8*rand(length(t),1));
e(100:115) = 30;
y = A*x+e;
%% Various estimates
xhat = sdpvar(6,1);