function [A,f,rho] = geomag(n,example,a,b,h)
%GRAVITY Test problem: 1-D gravity surveying model problem
%
% [A,f,rho] = geomag(n,example,a,b,h)
%
% Discretization of a 1-D model problem in gravity surveying, in which
% a mass distribution rho(s) is located at depth h, while the vertical
% component of the gravity field f(t) is measured at the surface.
%
% The resulting problem is a first-kind Fredholm integral equation
% with kernel
%    K(s,t) = h*(h^2 + (s-t)^2)^(-3/2) .
% The following three examples are implemented (example = 1 is default):
%    1: rho(t) = sin(pi*t) + 0.5*sin(2*pi*t),
%    2: rho(t) = piecewise linear function,
%    3: rho(t) = piecewise constant function.
% The problem is discretized by means of the midpoint quadrature rule
% with n points, leading to the matrix A and the vector rho.  Then the
% right-hand side is computed as f = A*rho.
%
% The s integration interval is fixed to [0,1], while the s integration
% interval [a,b] can be specified by the user. The default interval is
% [0,1], leading to a symmetric Toeplitz matrix.
%
% The parameter h is the depth at which the magnetic deposit is located,
% and the default value is h = 0.25. The larger the h, the faster the
% decay of the singular values.


% Initialization.
if (nargin<2), example = 1; end
if (nargin<4), a = 0; b = 1; end
if (nargin<5), h = 0.25; end
if isempty(example), example = 1; end
if isempty(a), a = 0; end
if isempty(b), b = 1; end

% Set up abscissas and matrix.
ds = 1/n;
dt = (b-a)/n;
s = ds*([1:n]' - 0.5);
t = a + dt*([1:n]' - 0.5);
[S,T] = meshgrid(s,t);
A = ds*h*ones(n,n)./(h^2 + (S-T).^2).^(3/2);

% Set up solution vector and right-hand side.
nt = round(n/3);
nn = round(n*7/8);
rho = ones(n,1);
switch example;
case 1
   rho = sin(pi*s) + 0.5*sin(2*pi*s);
case 2
   rho(1:nt)    = (2/nt)*[1:nt]';
   rho(nt+1:nn) = ((2*nn-nt) - [nt+1:nn]')/(nn-nt);
   rho(nn+1:n)  = (n - [nn+1:n]')/(n-nn);
case 3
   rho(1:nt) = 2*ones(nt,1);
otherwise
   error('Illegal value of example')
end
f = A*rho;
