function [time, rate] = binned_rate(spike_times, bin_width, dt, t_max)
% Calculates the firing rate with the binning method. The hist funciton is
% used to count the number of spikes in each bin. 
% Arguments: 
%           spike_times, 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(spike_times, bins) ./ bin_width;
for i = 2:length(bins)
    rate(round(bins(i - 1) / dt) + 1:round(bins(i) / dt)) = h(i);
end