function brownian_2d_simulate ( t, d, n )

%*****************************************************************************80
%
%% BROWNIAN_2D_PLOT simulates Brownian motion in 2D.
%
%  Licensing:
%
%    This code is distributed under the MIT license.
%
%  Modified:
%
%    06 April 2018
%
%  Author:
%
%    John Burkardt
%
%  Input:
%
%    integer N, the number of time steps to take. 
%
%    real D, the diffusion coefficient.  
%
%    real T, the total time.
%
%  Output:
%
%    real X(2,N+1), the initial position at time 0.0, and 
%    the N-1 successive locations of the particle.
%
  timestamp ( );
  fprintf ( 1, '\n' );
  fprintf ( 1, 'BROWNIAN_2D_SIMULATE:\n' );
  fprintf ( 1, '  MATLAB/Octave version %s:\n', version ( ) );
  fprintf ( 1, '  Simulate Brownian motion in two dimensions.\n' );
%
%  Simulate.
%
  if ( nargin < 1 )
    t = 1.0;
  end

  if ( nargin < 2 )
    d = 10.0;
  end

  if ( nargin < 3 )
    n = 1001;
  end
%
%  Set the time step.
%
  dt = t / n;
%
%  Make space X for the locations.
%
  x = zeros ( 2, n + 1 );
%
%  Choose stepsizes S that are normal random values.
%
  s = sqrt ( 2.0 * d * dt ) * randn ( 1, n );
%
%  The steps DX are a combination of a random stepsize and a random angle.
%
  a = randn ( 2, n );
  v = s ./ sqrt ( sum ( a.^2 ) );
  b = spdiags ( v', 0, n, n );
  dx(1:2,1:n) = a * b;
%
%  Each position X is the sum of the previous steps.
%
  x(1:2,2:n+1) = cumsum ( dx(1:2,1:n), 2 );
%
%  Transpose the data.
%
  x = x';
%
%  Save the data to a file.
%
  save ( 'brownian_2d_data.txt', 'x', '-ascii' );
%
%  Terminate.
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'BROWNIAN_2D_SIMULATE:\n' );
  fprintf ( 1, '  Normal end of execution.\n' );
  fprintf ( 1, '\n' );
  timestamp ( );

  return
end
function timestamp ( )

%*****************************************************************************80
%
%% TIMESTAMP prints the current YMDHMS date as a timestamp.
%
%  Licensing:
%
%    This code is distributed under the MIT license.
%
%  Modified:
%
%    14 February 2003
%
%  Author:
%
%    John Burkardt
%
  t = now;
  c = datevec ( t );
  s = datestr ( c, 0 );
  fprintf ( 1, '%s\n', s );

  return
end

