linprog (Matlab) vs glpk(Octave) - Why do I get different solutions? - matlab

I need to find an initial feasible solution for a network flow problem which is given by Nx = b, x >= 0. I used to the following OCTAVE code to do the job:
function [x,exitflag] = FIND_EXTREME_POINT(A,b)
%
% Function FIND_EXTREME_POINT
%
% Call: [x,fval] = FIND_EXTREME_POINT(A,b)
%
% MATLAB code for finding a extreme point of the set X = { x | Ax = b,
% x >= 0} by solving the auxiliary problem
%
% min 1'*y
% s.t. A*x + y = b
% x >= 0
% y >= 0
%
% either to receive a feasible basis solution or to return infeasibility
%
% Inputs:
% A - m*n matrix
% b = m*1 rhs
%
% Output:
% x - n*1 vector respresenting an extreme point
% exitflag - 0 if problem is infeasibile, 1 if the problem is feasible
%
% setup parameters for LP solver
[m,n] = size(A);
A_aux = [A eye(m)];
c_aux = [zeros(1,n) ones(1,m)]';
lb = [zeros(1,n+m)]';
ub = [];
ctype = repmat('S',1,m);
vartype = repmat('C',1,n+m);
% solve auxiliary LP
[xmin, fmin] = glpk(c_aux, A_aux, b, lb, ub, ctype, vartype, 1);
...% driving out artifical variables
The solution given by the glpk-solver matches to my handwritten notes.
For some reason I'm using MATLAB and I've got a problem with the following code:
function [x,exitflag] = FIND_EXTREME_POINT(A,b)
%
% Function FIND_EXTREME_POINT
%
% Call: [x,fval] = FIND_EXTREME_POINT(A,b)
%
% ....
%
% setup parameters for LP solver
[m,n] = size(A);
x = []; % output vector
A_aux = [A eye(m)];
c_aux = [zeros(1,n) ones(1,m)]';
lb = [zeros(1,n+m)]';
ub = [];
% solve auxiliary LP
[xmin,fval] = linprog(c_aux,[],[],A_aux,b,lb,ub);
... % driving out artifical variables
On the one hand the optimal solution xmin computed by the linprog-solver is feasible but on the other hand the function value fval is not zero but it should be so... Where is the mistake in my MATLAB code?
A little example:
N = [1 1 0 0 0 0 0;
-1 0 0 -1 0 0 0;
0 -1 1 0 0 -1 0;
0 0 -1 1 1 0 0;
0 0 0 0 0 1 1;
0 0 0 0 -1 0 -1];
b = [5 -5 0 0 0 0]';
OCTAVE gives me:
xmin =
5
0
0
0
0
0
0
0
0
0
0
0
0
fval =
0
MATLAB gives me:
xmin =
0.2184
4.7816
4.7816
4.7816
0.0000
0.0000
0.0000
0.0000
0.0000
0.0000
0.0000
0.0000
0.0000
fval =
5.8775e-016

Related

Matlab CPLEX: add multiple SOCP constraints in cplexmiqcp

I have written my problem in MATLAB, using CPLEX as the solver. Due issues that are beyond my control (it is feasible), the CPLEX class API screws up when solving my problem. So, based on post found elsewhere on the internet, I am trying to solve using the toolbox API.
To solve my problem I need to use cplexmiqcp, which has the inputs:
cplexmiqcp(H,f,Aineq,bineq,Aeq,beq,l,Q,r,sostype,sosind,soswt,varLB,varUB,vartype,x0,options);
I have multiple SOCP constraints, and using the class API, I am able to define each of them using a structure, such as:
for n=1:numQCs
cplex.Model.qc(n).a=QC.a{n};
cplex.Model.qc(n).Q=QC.Q{n,1};
cplex.Model.qc(n).sense=QC.sense{n};
cplex.Model.qc(n).rhs=QC.rhs{n};
cplex.Model.qc(n).lhs=QC.lhs{n};
end
But how do I define multiple quadratic constraints for cplexmiqcp inputs? These are l,Q,r. When I try creating a structure as before, I get "Error: incorrect l,Q,r."
The documentation for the cplexmiqcp toolbox function is here. Quoting the documentation, for l, Q, and r, we have:
l: Double column vector or matrix for linear part of quadratic constraints
Q: Symmetric double matrix or row cell array of symmetric double matrices for quadratic constraints
r: Double or double row vector for rhs of quadratic inequality constraints
So, when we want to create one quadratic constraint, we can give a double column vector, a symmetric double matrix, and a double for l, Q, and r, respectively. When we want to create multiple quadratic constraints, we need to provide a matrix, a row cell array of symmetric double matrices, and a row vector for l, Q, and r, respectively.
Consider the following simple model:
Minimize
obj: x1 + x2 + x3 + x4 + x5 + x6
Subject To
c1: x1 + x2 + x5 = 8
c2: x3 + x5 + x6 = 10
q1: [ - x1 ^2 + x2 ^2 + x3 ^2 ] <= 0
q2: [ - x4 ^2 + x5 ^2 ] <= 0
Bounds
x2 Free
x3 Free
x5 Free
End
The MATLAB code would look like the following:
H = [];
f = [1 1 1 1 1 1]';
Aineq = []
bineq = []
Aeq = [1 1 0 0 1 0;
0 0 1 0 1 1];
beq = [8 10]';
l = [0 0;
0 0;
0 0;
0 0;
0 0;
0 0;];
Q = {[-1 0 0 0 0 0;
0 1 0 0 0 0;
0 0 1 0 0 0;
0 0 0 0 0 0;
0 0 0 0 0 0;
0 0 0 0 0 0], ...
[0 0 0 0 0 0;
0 0 0 0 0 0;
0 0 0 0 0 0;
0 0 0 -1 0 0;
0 0 0 0 1 0;
0 0 0 0 0 0]};
r = [0 0];
sostype = [];
sosind = [];
soswt = [];
lb = [ 0; -inf; -inf; 0; -inf; 0];
ub = []; % implies all inf
ctype = []; % implies all continuous
options = cplexoptimset;
options.Display = 'on';
options.ExportModel = 'test.lp';
[x, fval, exitflag, output] = cplexmiqcp (H, f, Aineq, bineq, Aeq, beq,...
l, Q, r, sostype, sosind, soswt, lb, ub, ctype, [], options);
fprintf ('\nSolution status = %s \n', output.cplexstatusstring);
fprintf ('Solution value = %f \n', fval);
disp ('Values =');
disp (x');

How to formulate this expression

I am new to MATLAB and I want to formulate the following lease square expression in Matlab. I have some codes that I am typing here. But the optimization problem solution seems not to be correct. Does anyone has an idea why?
First, I want to solve the heat equation
$$T_t(x,t) = - L_x . T(x,t) + F(x,t)$$
where L_x is Laplacian matrix of the graph.
then find y from the following least square.
$$ \min_y \sum_{j} \sum_{i} (\hat{T}_j(t_i) - T_j(t_i, y))^2$$
Thanks in advance!!
Here is my code:
%++++++++++++++++ main ++++++++++++++++++++
% incidence matrix for original graph
C_hat = [ 1 -1 0 0 0 0;...
0 1 -1 0 0 -1;...
0 0 0 0 -1 1;...
0 0 0 1 1 0;...
-1 0 1 -1 0 0];
% initial temperature for each vertex in original graph
T_hat_0 = [0 7 1 9 4];
[M_bar,n,m_bar,T_hat_heat,T_hat_temp] = simulate_temp(T_hat_0,C_hat);
C = [ 1 1 -1 -1 0 0 0 0 0 0;...
0 -1 0 0 1 -1 1 0 0 0;...
0 0 1 0 0 1 0 -1 -1 0;...
0 0 0 1 0 0 -1 0 1 -1;...
-1 0 0 0 -1 0 0 1 0 1];
%
% initial temperature for each vertex in original graph
T_0 = [0 7 1 9 4];
%
% initial temperature simulation
[l,n,m,T_heat,T_temp] = simulate_temp(T_0,C);
%
% bounds for variables
lb = zeros(m,1);
ub = ones(m,1);
%
% initial edge weights
w0 = ones(m,1);
% optimization problem
% w = fmincon(#fun, w0, [], [], [], [], lb, ub);
%++++++++++++++++++++ function++++++++++++++++++++++++++++
function [i,n,m,T_heat,T_temp] = simulate_temp(T,C)
%
% initial conditions
delta_t = 0.1;
M = 20; %% number of time steps
t = 1;
[n,m] = size(C);
I = eye(n);
L_w = C * C';
T_ini = T';
Temp = zeros(n,1);
% Computing Temperature
%
for i=1:M
K = 2*I + L_w * delta_t;
H = 2*I - L_w * delta_t;
%
if i == 1
T_heat = (K \ H) * T_ini;
%
t = t + delta_t;
else
T_heat = (K \ H) * Temp;
%
t = t + delta_t;
end
% replacing column of T_final with each node temperature in each
% iteration. It adds one column to the matrix in each step
T_temp(:,i) = T_heat;
%
Temp = T_heat;
end
end
%++++++++++++++++++ function+++++++++++++++++++++++++++++++++++++++++
function w_i = fun(w);
%
for r=1:n
for s=1:M_bar
w_i = (T_hat_temp(r,s) - T_temp(r,s)).^2;
end
end
To give a more clear answer, I need more information about what form you have the functions F_j and E_j in.
I've assumed that you feed each F_j a value, x_i, and get back a number. I've also assumed that you feed E_j a value x_i, and another value (or vector) y, and get back a value.
I've also assumed that by 'i' and 'j' you mean the indices of the columns and rows respectively, and that they're finite.
All I can suggest without knowing more info is to do this:
Pre-calculate the values of the functions F_j for each x_i, to give a matrix F - where element F(i,j) gives you the value F_j(x_i).
Do the same thing for E_j, giving a matrix E - where E(i,j) corresponds to E_j(x_i,y).
Perform (F-E).^2 to subtract each element of F and E, then square them element-wise.
Take sum( (F-E).^2**, 2)**. sum(M,2) will sum across index i of matrix M, returning a column vector.
Finally, take sum( sum( (F-E).^2, 2), 1) to sum across index j, the columns, this will finally give you a scalar.

matlab: praticle state simulation

Lets say I want to simulate a particle state, which can be normal (0) or excited (1) in given frame. The particle is in excited state f % of time. If the particle is in excited state, it lasts for ~L frames (with poisson distribution). I want to simulate that state for N time points. So the input is for example:
N = 1000;
f = 0.3;
L = 5;
and the result will be something like
state(1:N) = [0 0 1 1 1 1 0 0 0 0 1 1 1 0 0 0 0 0 0 0 0 0 1 1 1 1 1 0 0 0 0 0 ... and so on]
with sum(state)/N close to 0.3
How to do that?
Thanks!
%% parameters
f = 0.3; % probability of state 1
L1 = 5; % average time in state 1
N = 1e4;
s0 = 1; % init. state
%% run simulation
L0 = L1 * (1 / f - 1); % average time state 0 lasts
p01 = 1 / L0; % probability to switch from 0 to 1
p10 = 1 / L1; % probability to switch from 1 to 0
p00 = 1 - p01;
p11 = 1 - p10;
sm = [p00, p01; p10, p11]; % build stochastic matrix (state machine)
bins = [0, 1]; % possible states
states = zeros(N, 1);
assert(all(sum(sm, 2) == 1), 'not a stochastic matrix');
smc = cumsum(sm, 2); % cummulative matrix
xi = find(bins == s0);
for k = 1 : N
yi = find(smc(xi, :) > rand, 1, 'first');
states(k) = bins(yi);
xi = yi;
end
%% check result
ds = [states(1); diff(states)];
idx_begin = find(ds == 1 & states == 1);
idx_end = find(ds == -1 & states == 0);
if idx_end(end) < idx_begin(end)
idx_end = [idx_end; N + 1];
end
df = idx_end - idx_begin;
fprintf('prob(state = 1) = %g; avg. time(state = 1) = %g\n', sum(states) / N, mean(df));
The average length of the excited state is 5. The average length of the normal state, should thus be around 12 to obtain.
The strategy can be something like this.
Start in state 0
Draw a random number a from a Poisson distribution with mean L*(1-f)/f
Fill the state array with a zeroes
Draw a random number b from a Poission distribution with mean L
Fill the state array witb b ones.
Repeat
Another option would be to think in terms of switching probabilities, where the 0->1 and 1->0 probabilities are unequal.

MATLAB matrix not formatting correctly

I have some code below, and I cant seem to get the matrices formatted correctly. I have been trying to get the matrices to look more professional (close together) with \t and fprintf, but cant seem to do so. I am also having some trouble putting titles for each columns of the matrix. Any help would be much appreciated!
clear all
clc
format('bank')
% input file values %
A = [4 6 5 1 0 0 0 0 0; 7 8 4 0 1 0 0 0 0; 6 5 9 0 0 1 0 0 0; 1 0 0 0 0 0 -1 0 0; 0 1 0 0 0 0 0 -1 0; 0 0 1 0 0 0 0 0 -1];
b = [480; 600; 480; 24; 20; 25];
c = [3000 4000 4000 0 0 0 0 0 0];
% Starting xb %
xb = [1 2 3 4 5 6]
% Starting xn %
xn = [7 8 9]
cb = c(xb)
cn = c(xn)
% Get B from A %
B = A(:,xb)
% Get N from A %
N = A(:,xn)
% Calculate z %
z = ((cb*(inv(B))*A)-c)
% Calculate B^(-1) %
Binv = inv(B)
% Calculate RHS of row 0 %
RHS0 = cb*Binv*b
% Calculates A %
A = Binv*A
%STARTING Tableau%
ST = [z RHS0;A b]
for j=1:A
fprintf(1,'\tz%d',j)
end
q = 0
while q == 0
m = input('what is the index value of the ENTERING variable? ')
n = input('what is the index value of the LEAVING variable? ')
xn(xn==m)= n
xb(xb==n) = m
cb = c(xb)
cn = c(xn)
B = A(:,xb)
N = A(:,xn)
Tableuz = (c-(cb*(B^(-1))*A))
RHS0 = (cb*(B^(-1))*b)
TableuA = ((B^(-1))*A)
Tableub = ((B^(-1))*b)
CT = [Tableuz RHS0; TableuA Tableub];
disp(CT)
q = input('Is the tableau optimal? Y-1, N-0')
end
I didn't dig into what you are doing really deeply, but a few pointers:
* Put semicolons at the end of lines you don't want printing to the screen--it makes it easier to see what is happening elsewhere.
* Your for j=1:A loop only prints j. I think what you want is more like this:
for row = 1:size(A,1)
for column = 1:size(A,2)
fprintf('%10.2f', A(row,column));
end
fprintf('\n');
end
If you haven't used the Matlab debugger yet, give it a try; it makes a lot of these problems easier to spot. All you have to do to start it is to add a breakpoint to the file by clicking on the dash(-) next to the line numbers and starting the script. Quick web searches can turn up the solution very quickly too--someone else has usually already had any problem you're going to run into.
Good luck.
Try using num2str with a format argument of your desired precision. It's meant for converting matrices to strings. (note: this is different than mat2str which serializes matrices so they can be deserialized with eval)

Solving a MATLAB equation

I have the following equation:
((a^3)-(4*a^2))+[1 0 2;-1 4 6;-1 1 1] = 0
How do I solve this in MATLAB?
Here is one possibility:
% A^3 - 4*A^2 + [1 0 2;-1 4 6;-1 1 1] = 0
% 1) Change base to diagonalize the constant term
M = [1 0 2;-1 4 6;-1 1 1];
[V, L] = eig(M);
% 2) Solve three equations "on the diagonal", i.e. find a root of
% x^4 - 4*x^3 + eigenvalue = 0 for each eigenvalue of M
% (in this example, for each eigenvalue I choose the 3rd root,
% which happens to be real)
roots1 = roots([1 -4 0 L(1,1)]); r1 = roots1(3);
roots2 = roots([1 -4 0 L(2,2)]); r2 = roots2(3);
roots3 = roots([1 -4 0 L(3,3)]); r3 = roots3(3);
% 3) Build matrix solution and transform with inverse change of base
SD = diag([r1, r2, r3]);
A = V*SD*inv(V) % This is your solution
% The error should be practically zero
error = A^3 - 4*A^2 + [1 0 2;-1 4 6;-1 1 1]
norm(error)
(The error is actually of the order of 10^-14.)