% M-file (i.e. Matlab script) to invert a matrix stored in GDX

% we want to read the matrix as square and dense, essentially as
% A(i,i) where i is stored in the GDX also, so we filter both
% dimensions.  This way, we get exactly the structure we want
% regardless of the universe in the GDX or zero rows/cols in the
% matrix

rs.name = 'i';
rs.form = 'full';
r = rgdx('a.gdx',rs);

ra.name = 'a';
ra.form = 'full';
ra.uels{1} = r.uels{1};
ra.uels{2} = r.uels{1};
a = rgdx('a.gdx',ra);

if 2 ~= a.dim
  error('bad a.dim: we expected a 2-dimensional matrix');
end

% inverse matrix is very similar to A: same size, etc
ainv = a;
ainv.val = inv(a.val);
ainv.ts = 'inverse of a computed in Matlab via inv(a)';
ainv.name = 'inva';

% introduce some noise to exercise the check for a bad inverse
% ainv.val(1,1) = ainv.val(1,1) * (1 + 1e-8);

wgdx('c.gdx', ainv)

fprintf (1, 'Matlab script all done: inverse of A written to c.gdx\n');

exit
