function [time, rate] = binned_rate(spikes, bin_width, dt, t_max)
% PSTH computed with binning method. 
% The hist funciton is used to count the number of spikes in each bin. 
%
% [time, rate] = binned_rate(spikes, bin_width, dt, t_max)
%
% Arguments: 
%   spikes   : vector containing the times of the spikes.
%   bin_width: the width of the bins in seconds.
%   dt       : the temporal resolution.
%   t_max    : the tiral duration.
%
% Returns:
%   two vectors containing the time and the rate.

    time = 0:dt:t_max-dt;
    bins = 0:bin_width:t_max;
    rate = zeros(size(time));
    h = hist(spikes, bins) ./ bin_width;
    for i = 2:length(bins)
        rate(round(bins(i - 1) / dt) + 1:round(bins(i) / dt)) = h(i);
    end
end

