Gurobi in Matlab without objective function - matlab

I am using Gurobi in Matlab to determine whether a system of linear equalities and linear inequalities has at least one solution. I don't have an objective function to minimise/maximise.
This is my code (I haven't posted the actual content of the matrices Aineq, Aeq, bineq, beq)
clear model;
model.A=[Aineq; Aeq];
model.obj=[];
model.sense=[repmat('<', size(Aineq,1),1); repmat('=', size(Aeq,1),1)];
model.rhs=full([bineq; beq]);
params.outputflag = 0;
result=gurobi(model, params);
if isfield(result,'x')
exists=1;
else
exists=0;
end
Question: what should I set as objective function? If I write model.obj=[]; as above I get
Error using gurobi
Incorrect size(model.obj)
If I delete the model line I get
Error using gurobi
model must contain fields: A, obj, sense, and rhs
This question is related to mine but it doesn't explain what to put in place of the objective function.

Unfortunately I don't have the needed reputation to comment, so this is an answer.
It's important that your matrix A is a sparse matrix, because Gurobi's MATLAB API only accepts sparse matrices: model.A=sparse([Aineq; Aeq]). Then it should work by just removing the line model.obj = [] from your code. If no objective is passed to Gurobi, it will automatically use 0 as the objective function, so that your model will minimize 0 in subject to your constraints. In this case every feasible solution is optimal and satisfies your constraints. Alternatively, you could do this by hand with
model.obj = zeros(size(model.A, 2), 1);

Related

Mixed Integer Quadratic Programming with linear constraints in Matlab calling Gurobi

I have some troubles to understand how to implement the following MIQP (Mixed Integer Quadratic Programming) with linear constraints in Matlab calling Gurobi.
Let me explain in a schematic way my setting.
(1) x is the unknown and it is a column vector with size 225x1.
(2) The objective function (which should be minimised wrto x) looks like
which can be rewritten as
I have a Matlab script computing alpha, Q,c (Q,c sparse) when some_known_parameters1 are given:
function [alpha, Q,c]=matrix_objective_function(some_known_parameters1)
%...
end
(3) The constraints are linear in x, include equalities and inequalities, and are written in the form
I have a Matlab script computing Aeq,beq,Aineq,bineq (Aeq,Aineq sparse) when some_known_parameters2 is given:
function [Aeq,beq,Aineq,bineq]=constraints(some_known_parameters2)
%...
end
(4) Some components of x are restricted to be in {0,1}. I have a Matlab script producing a string of letters B (binary), C (continous) when some_known_parameters3 is given:
function type=binary_continuous(some_known_parameters3)
%...
end
Now, I need to put together (1)-(4) using Gurobi. I am struggling to understand how. I found this example but it looks very cryptic to me. Below I report some lines I have attempted to write, but they are incomplete and I would like your help to complete them.
clear
rng default
%Define some_known_parameters1,
some_known_parameters2,some_known_parameters3 [...]
%1) generate alpha,Q,c,Aeq,beq,Aineq,bineq,type with Q,c,Aeq, Aineq sparse
[alpha, Q,c]=matrix_objective_function(some_known_parameters1)
[Aeq,beq,Aineq,bineq]=constraints(some_known_parameters2)
type=binary_continuous(some_known_parameters3)
%2) Set up Gurobi
clear model;
model.A=[Aineq; Aeq];
model.rhs=full([bineq(:); beq(:)]);
model.sense=[repmat('<', size(Aineq,1),1); repmat('=', size(Aeq,1),1)];
model.Q=Q; %not sure?
model.alpha=alpha; %not sure?
model.c=c; %not sure?
model.vtype=type;
result=gurobi(model); %how do I get just the objective function here without the minimiser?
Questions:
(1) I'm not sure about
model.Q=Q;
model.alpha=alpha;
model.c=c;
I'm just trying to set the matrices of the objective function using the letters provided here but it gives me error. The example here seems to me doing
model.Q=Q;
model.obj=c;
But then how do I set alpha? Is it ignoring it because it does not change the set of solutions?
(2) How do I get as output stored in a matrix just the minimum value of the objective function without the corresponding x?
(1) You're right, there's no need to pass the constant alpha since it doesn't affect the optimal solution. Gurobi's MATLAB API only accepts sparse matrices. Furthermore model.obj is always the c vector in the problem statement:
model.Q = sparse(Q);
model.obj = c;
(2) To get the optimal objective value, you first need to pass your model to gurobi and solve it. Then you can access it via the objval attribute:
results = gurobi(model);
val = results.objval + alpha

Unable to code non linear equation in MATLAB R2013a - MATLAB giving warning message

I wanted to solve the following equation in MATLAB R2013a using the Symbolic Math Toolbox.
(y/x)-(((1+r)^n)-1)/r=0 where y,x and n>3 are given and r is the dependent variable
I tried myself & coded as follows:
f=solve('(y/x)-(((1+r)^n)-1)/r','r')
but as the solution for r is not exact i.e. it is converging on successive iterations hence MATLAB is giving a warning output with the message
Warning: Explicit solution could not be found.
f =
[ empty sym ]
How do I code this?
There are an infinite number of solutions to this for an unspecified value of n > 3 and unknown r. I hope that it's pretty clear why – it's effectively asking for a greater and greater number of roots of (1+r)^n. You can find solutions for fixed values of n, however. Note that as n becomes larger there are more and more solutions and of course some of them are complex. I'm going to assume that you're only interested in real values of r. You can use solve and symbolic math for n = 4, n = 5, and n = 6 (for n = 6, the solution may not be in a convenient form):
y = 441361;
x = 66990;
n = 5;
syms r;
rsol = solve(y/x-((1+r)^n-1)/r==0,r,'IgnoreAnalyticConstraints',true)
double(rsol)
However, the question is "do you need all the solutions or just a particular solution for a given value of n"? If you just need a particular solution, you shouldn't be using symbolic math at all as it's slower and has practical issues like the ones you're experiencing. You can instead just use a numerical approach to find a zero of the equation that is near a specified initial guess. fzero is the standard function for solving this sort of problem in a single variable:
y = 441361;
x = 66990;
n = 5;
f = #(r)y/x-((1+r).^n-1)./r;
r0 = 1;
rsol = fzero(f,r0)
You'll see that the value returned is the same as one of the solutions from the symbolic solution above. If you adjust the initial guess r0 (say r0 = -3), it will return the other solution. When using numeric approaches in cases when there are multiple solutions, if you want specific solutions you'll need to know about the behavior of your function and you'll need to add some clever extra code to choose initial guesses.
I think you forgot to define n as well.
f=solve('(y/x)-(((1+r)^n)-1)/r=0','n-3>0','r','n')
Should solve your problem :)

YALMIP is returning that a program is infeasible when it is not

I'm having a problem trying to use YALMIP; I suspect I'm doing something silly and I would greatly appreciate if someone pointed out what it is.
I'm trying to solve some SDPs. When I don't define an objective, YALMIP returns a solution (implying that the problem is feasible). However, when I attach an objective to it, YALMIP returns that the problem is infeasible, which has left me a bit perplexed.
Here's the code for the simplest SDP I could cook up in which the above happens. Declaring the variables and setting the constraints is as follows:
y = sdpvar(6,1);
M = sdpvar(3,3);
C = [0,0,0,0,0,0; 0,0,0,0,0,0; -2,0,1.8,0,2,1; 0,0,0,0,0,0; 1,0,-1,0,-1.2,0;
0,0,0,0,0,0;];
F = [C*y==0, y(6) == 1, M>=0];
F = [F,M(1,1) == y(1), M(2,1) == y(2), M(3,1) == y(3),...
M(2,2) == y(4), M(3,2) == y(5), M(3,3) == y(6)];
Now if I merely ask YALMIP to find a feasible solution with
solvesdp(F)
it returns
info: 'Successfully solved (LMILAB)'
problem: 0
and some feasible M and y (I've checked that they indeed are). However, if I append the objective "minimise y(3)" (or indeed any linear combination of the entries of y) with
solvesdp(F,y(3))
it returns that the problem is infeasible:
info: 'Infeasible problem (LMILAB)'
problem: 1
and y and M are full of "NaN" tokens.
Many thanks in advance.
LMILAB should not be used together with YALMIP.
http://users.isy.liu.se/johanl/yalmip/pmwiki.php?n=Solvers.LMILAB
The solver in LMILAB has many deficiencies, and one which becomes crucial here is the fact that the solver lacks support for inequalities. To circumvent this, YALMIP adds double-sided inequalities, which completely destroys the numerical procedures of LMILAB.
Install a more general (and modern) solver such as SeDuMi, SDPT3, or Mosek
http://users.isy.liu.se/johanl/yalmip/pmwiki.php?n=Category.SemidefiniteProgrammingSolver
BTW, you are redundantly defining additional variables y. No reason to have them as separate decision variables and then encode how they relate to M. Simply extract them
y = M(find(tril(ones(3))));

Using coupled system of PDEs in modelica

Just few questions, i hope someone will find time to answer :).
What if we have COUPLED model example: system of n indepedent variables X and n nonlinear partial differential equations PDEf(X,PDEf(X)) with respect to TIME that depends of X,PDEf(X)(partial differential equation depending of variables X ). Can you give some advice? Here is one example:
Let’s say that c is output, or desired variable. Let’s say that r is independent variable.Partial differential equation looks like:
∂c/∂t=D*1/r+∂c/∂r+2(D* (∂^2 c)/(∂r^2 ))
D=constant
r=0:0.1:Rp- Matlab syntaxis, how to represent same in Modelica (I use integrator,but didn't work)?
Here is a code (does not work):
model PDEtest
/* Boundary conditions
1. delta(c)/delta(r)=0 for r=0
2. delta(c)/delta(r)=-j*d for r=Rp*/
parameter Real Rp=88*1e-3; // length
parameter Real initialConc=1000;
parameter Real Dp=1e-14;
parameter Integer np=10; // num. of points
Real cp[np](start=fill(initialConc,np));
Modelica.Blocks.Continuous.Integrator r(k=1); // independent x1
Real j;
protected
parameter Real dr=Rp/np;
parameter Real ts= 0.01; // for using when loop (sample(0,ts) )
algorithm
j:=sin(time); // this should be indepedent variable like x2
r.u:=dr;
while r.y<=Rp loop
for i in 2:np-1 loop
der(cp[i]):=2*Dp/r.y+(cp[i]-cp[i-1])/dr+2*(Dp*(cp[i+1]-2*cp[i]+cp[i-1])/dr^2);
end for;
if r.y==Rp then
cp[np]:=-j*Dp;
end if;
cp[1]:=if time >=0 then initialConc else initialConc;
end while;
annotation (uses(Modelica(version="3.2")));
end PDEtest;
Here are more questions:
This code don’t work in OpenModelica 1.8.1, also don’t work in Dymola 2013demo. How can we have continuos function of variable c, not array of functions ?
Can we place values of array cp in combiTable? And how?
If instead “algorithm” stay “equation” code can’t be succesfull checked.Why? In OpenModelica, error is :could not flattening model :S.
Is there any simplified way to use a set of equation (PDE’s) that are coupled? I know for PDEs library in Modelica, but I think they are complicated. I want to write a function for solving PDE and call these function in “main model”, so that output of function be continuos function of “c”.I don’t know what for doing with array of functions.
Can you give me advice how to understand Modelica language, if we “speak” like in Matlab? For example: Values of independent variable r,we can specife in Matlab, like r=0:TimeStep:Rp…How to do same in Modelica? And please explain me how section “equation” works, is there similarity with Matlab, and is there necessary sequancial approach?
Cheers :)
It's hard to answer your question, since you assuming that Modelica ~ Matlab, but that's not the case. So I won't comment your code, since it's really wrong. Let me give you an example model to the burger equation. Maybe you could use it as starting point.
model burgereqn
Real u[N+2](start=u0);
parameter Real h = 1/(N+1);
parameter Integer N = 10;
parameter Real v = 234;
parameter Real Pi = 3.14159265358979;
parameter Real u0[N+2]={((sin(2*Pi*x[i]))+0.5*sin(Pi*x[i])) for i in 1:N+2};
parameter Real x[N+2] = { h*i for i in 1:N+2};
equation
der(u[1]) = 0;
for i in 2:N+1 loop
der(u[i]) = - ((u[i+1]^2-u[i-1]^2)/(4*(x[i+1]-x[i-1])))
+ (v/(x[i+1]-x[i-1])^2)*(u[i+1]-2*u[i]+u[i+1]);
end for;
der(u[N+2]) = 0;
end burgereqn;
Your further questions:
cp is an continuous variable and the array is representing
every discretization point.
Why you should want to do that, as far as I understand cp is
your desired solution variable.
You should try to use almost always equation section
algorithm sections are usually used in functions. I'm pretty
sure you can represent your desire behaviour with equations.
I don't know that library, but the hard thing on a pde is the
discretization and the solving it self. You may run into issues
while solving the pde with a modelica tool, since usually
a Modelica tool has no specialized solving algorithm for pdes.
Please consider for that question further references. You could
start with Modelica.org.

Problems which matlab is good for

Let me ask whether using Matlab for my particular problem is nonsense or some people do the similar.
I have an initial sequence S(1), where each term is a 2D point.
I create a new sequence S(2) by inserting a new term point p
between each consecutive 2 term points p(i) and p(i+1).
Where p is a function f of 4 term points of nearest indices on S(2).
Namely,
p= f( p(i-1),p(i),p(i+1),p(i+2) )
And the function f is written in a C like style
but not in the pure style of matrix language.
In the same way , I repeat generating the new longer sequence S(i+1) up to S(m).
The above may be vague for you, but please give some advice.
I do not ask whether Matlab is the best choice for the problem , but whether no expert will use Matlab for such a problem or some will.
Thank you in advance.
It heavily depends on f. If f could be coded efficiently in Matlab or you are willing to spend the time to MEX it (Matlab C extension), then Matlab will perform efficiently.
The code could be vectorized like this:
f = #(x) mean(x,3);
m=3;
S{1}=[1,2,3;4,5,6];
for i=2:m
S{i} = cat(3,...
[[0;0] S{i-1}(:,1:end-2)],...
S{i-1}(:,1:end-1),...
S{i-1}(:,2:end),...
[S{i-1}(:,3:end) [0;0]]);
S{i} = [f(S{i}) [0;0]];
S{i} = cat(3,S{i-1},S{i});
S{i} = permute(S{i},[1 3 2]);
S{i} = S{i}(:,:);
S{i}(:,end)=[];
end
Yes, Matlab seems to be suitable for such a task. For the data structure of your list of sequences, consider using cell arrays. You could have S as a cell array, and S{1} would correspond to your S(1), and could again be a cell array of points, or a usual matrix if points are just pairs or triples of numbers.
As an alternative, Python in my opinion is particulary strong when it comes to all kind of sequences.