Search This Blog

Tuesday, May 21, 2013

Matlab example for gurobi, installation instructions and simplest example

Setting up Gurobi for MATLAB

To begin, you'll need to tell MATLAB where to find the Gurobi routines. We've provided a script to assist you with this. The Gurobi MATLAB setup script, gurobi_setup.m, can be found in the /matlab directory of your Gurobi installation (e.g., /opt/gurobi550/linux64/matlab for the 64-bit Linux version of Gurobi 5.5). To get started, type the following commands within MATLAB to change to the matlab directory and call gurobi_setup:
>> cd /opt/gurobi550/linux64/matlab
>> gurobi_setup
You will need to be careful that the MATLAB binary and the Gurobi package you install both use the same instruction set. For example, if you are using the 64-bit version of MATLAB, you'll need to install the 64-bit version of Gurobi, and you'll need to use the 64-bit Gurobi MATLAB libraries (i.e., the ones included with the 64-bit version of Gurobi). This is particularly important on Windows systems, where the error messages that result from instruction set mismatches can be quite cryptic.



Example

Let us now turn our attention to an example of using Gurobi to solve a simple MIP model. Our example optimizes the following model:
maximize x + y + 2 z    
subject to x + 2 y + 3 z $\leq$ 4
  x + y     $\geq$ 1
  x, y, z binary  
Note that this is the same model that was modeled and optimized in the C Interface section. This is the complete source code for our example (also available in /examples/matlab/mip1.m)...
names = {'x'; 'y'; 'z'};

try
    clear model;
    model.A = sparse([1 2 3; 1 1 0]);
    model.obj = [1 1 2];
    model.rhs = [4; 1];
    model.sense = '<>';
    model.vtype = 'B';
    model.modelsense = 'max';

    clear params;
    params.outputflag = 0;
    params.resultfile = 'mip1.lp';

    result = gurobi(model, params);

    disp(result)

    for v=1:length(names)
        fprintf('%s %d\n', names{v}, result.x(v));
    end

    fprintf('Obj: %e\n', result.objval);

catch gurobiError
    fprintf('Error reported\n');
end 
 
 
 
 
 ==========================================================
 
copy and paste this program to the matlab prompt and see result as follows: 
 
          status: 'OPTIMAL'
     versioninfo: [1x1 struct]
          objval: 3
         runtime: 0.0010
               x: [3x1 double]
           slack: [2x1 double]
        objbound: 3
       itercount: 0
    baritercount: 0
       nodecount: 0

x 1
y 0
z 1
Obj: 3.000000e+000