Examples of numerical solution of stochastic differential equation(SDE)?

I want to simulate a nonlinear stochastic differential equation $${\rm d}X_t = f(X_t) {\rm d}t + g(X_t){\rm d}B_t$$ where $f,g \in C^{\infty}({\mathbb R}^n ,{\mathbb R})$ and $B_t$ is one-dimensional standard brownian motion. How can I do it by MATLAB?

A good simulation file for a similar equation might be helpful.

Check out this paper by Des Higham and the SDETools MATLAB toolbox.

• @Mohammad Khosravi: I was just in the process of typing out my own answer - I'm the author of SDETools so I can't say much more. From your notation, I assume that you have an Itô SDE. First, learn about the very simple Euler-Maruyama method. The Higham paper is a gentle intro, and then if you'e at all familiar with Matlab's ODE suite (e.g., ode45) you should find SDETools easy to use. – horchler Sep 2 '13 at 15:27
• @Mohammad : the Des Higham paper cited by Juan is excellent. You can probably find it for free if you do a little Googling (I did). Warning: there may be a link to some Matlab files that is out-of-date. The files are now at personal.strath.ac.uk/d.j.higham/algfiles.html . Second warning: I am having a lot of trouble getting the Octave versions of those files (there is a link to the Octave files at the link I just gave) to work. I am an Octave/Matlab novice. I have not tried the Matlab versions yet. – Stefan Smith Sep 4 '13 at 22:47
• @Mohammad : I just downloaded and executed the Matlab files at the link I gave above, in Matlab 2013, and they all ran just fine, despite my trouble with the Octave files I mentioned. – Stefan Smith Sep 5 '13 at 19:10

$$dx_{t}=2x_{t} dt +x_{t} dw_{t}\\x_{0}=1$$

% EM Euler-Maruyama method on linear SDE
%
% SDE is dX = lambda*X dt + mu*X dW, X(0) = Xzero,
% where lambda = 2, mu = 1 and Xzero = 1.
%
% Discretized Brownian path over [0,1] has dt = 2^(-8).
% Euler-Maruyama uses timestep R*dt.

state=randn(100)
lambda = 2;
mu = 1;
Xzero = 1;   % problem parameters
T = 1;
N = 2^8;
dt = 1/N;
dW = sqrt(dt)*randn(1,N); % Brownian increments
W = cumsum(dW); % discretized Brownian path
Xtrue = Xzero*exp((lambda-0.5*mu^2)*([dt:dt:T])+mu*W);
plot([0:dt:T],[Xzero,Xtrue]), hold on
R = 4;
Dt = R*dt;
L = N/R; % L EM steps of size Dt = R*dt
Xem = zeros(1,L); % preallocate for efficiency
Xtemp = Xzero;
for j = 1:L
Winc = sum(dW(R*(j-1)+1:R*j));
Xtemp = Xtemp + Dt*lambda*Xtemp + mu*Xtemp*Winc;
Xem(j) = Xtemp;
end
plot([0:Dt:T],[Xzero,Xem]), hold off