% M-file (i.e. Matlab script) for gdxmrw_qp2 from GAMS datalib

% first define the data in Matlab, and make sure it has the expected
% form for this example of sending to GDX

mean = [ 8.0 9.0 12.0 7.0 ]';
cov =  [    4         3         -1        0  ;
            3         6          1        0  ;
           -1         1         10        0  ;
            0         0          0        0  ];

[N,NN] = size(mean);
if NN ~= 1
   error('mean data is bogus: NN ~= 1');
end
[MM,NN] = size(cov);
if MM ~= N
   error('cov data is bogus: NN ~= N');
end
if NN ~= N
   error('cov data is bogus: MM ~= N');
end

% The data looks good.  Write it to GDX now

fnameData = 'qp2data.gdx';
fnameResult = 'qp2frontier.gdx';

if exist(fnameData,'file')
  delete (fnameData);
end
if exist(fnameResult,'file')
  delete (fnameResult);
end
if exist(fnameData,'file')
  error([ 'File ', fnameData, ' still exists' ]);
end
if exist(fnameResult,'file')
  error([ 'File ', fnameResult, ' still exists' ]);
end

iwgdx(fnameData,'mean','cov');
if ~ exist(fnameData,'file')
   error([ 'File ', fnameData, ' does not exist' ]);
end

% run GAMS to do the analysis
flag = system (['gams gdxmrw_qp2 lo=2 --INFILE=', fnameData, ...
                ' --OUTFILE=', fnameResult ]);
if flag ~= 0
  error('gams run failed: rc = %d', flag);
end
if ~ exist(fnameResult,'file')
   error([ 'Results file ', fnameResult, ' does not exist after gams run' ]);
end

% visualize the results
ss = irgdx(fnameResult);

figure(1);
plot (ss.t,ss.v);
title('efficient frontier for QP2 example');
xlabel('mean return');
ylabel('variance');
