% Exercise 1.1
%
% This MATLAB script accompanies the chapter "Distinguishing between models
% of perceptual decision making" by J. Ditterich in the book "An
% Introduction to Model-Based Cognitive Neuroscience". It demonstrates the
% distribution of decision times resulting from an integration-to-threshold
% mechanism. Please note that this script has been optimized for
% readability, not execution speed.
% 
% J. Ditterich, 12/2012

clear;
close all;

% Parameters
dist_mean   = 1; % mean of normal distribution from which random samples are drawn
dist_sd     = 3; % standard deviation of normal distribution from which random samples are drawn
thr         = 25; % decision threshold (A)
trials      = 20000; % number of trials to be simulated

% Let's go...
dt_vec = []; % vector of decision times
disp('Starting simulation...');

for i = 1 : trials % simulate each trial
    cur_sum = 0; % initialize current sum
    num_samples = 0; % initialize number of drawn samples
    
    while 1 % loop for sequential sampling
        cur_samp = random('norm',dist_mean,dist_sd); % draw a new random number
        num_samples = num_samples + 1; % update number of random samples (reflecting decision time)
        cur_sum = cur_sum + cur_samp; % update the sum
        
        if cur_sum > thr % Did we exceed the upper threshold?
            dt_vec = [dt_vec num_samples]; % store the decision time
            break; % terminate the loop for this trial
        end;
        
        if cur_sum < -thr % Did we cross the lower threshold?
            dt_vec = [dt_vec num_samples]; % store the decision time
            break; % terminate the loop for this trial
        end;
    end;
    
    if mod(i,1000) == 0
        disp([num2str(i) ' trials completed.']);
    end;
end;

hist(dt_vec,25); % plot a histogram of the decision times
title('Distribution of decision times');
