% Control3_3.m
% Solution to problem 3 of control 3. May.2018
% J.M.Soler, May.2018

% Set parameters
clear
nc = 21;                  % number of cells
nt = 1e5;                 % number of time steps (jump attempts)

% Find jump probabilities
x1 = 1:nc;                % cells of origin
x1 = repmat(x1,nc,1);
x2 = x1';                 % cells of destination
d = abs(x1-x2);           % distance between origin and destination
p = (d+10)./(5*d+10);     % jump probabilities

% Find positions as a function of time
x(1) = 1;                 % initial position
for it = 1:nt-1
    x1 = x(it);           % cell of origin
    x2 = randi(nc);       % destination cell  
    if p(x1,x2)>rand;     % accept jump
        x(it+1) = x2;  
    else                  % stay at original cell
        x(it+1) = x1;
    end
end

% Find cell probabilities
for xc = 1:nc
    pc(xc) = sum(x==xc)/nt;   % fraction of times at cell xc
end
Pcenter = pc(ceil(nc/2))      % probability at center cell
Pends = pc(1)+pc(end)         % prob. of cells at both extremes
Podd = sum(pc(1:2:end))       % prob. of odd cells

% Find jump frequencies
dx = x(2:nt)-x(1:nt-1);       % jump displacements at each time
for d = 0:nc-1
    pd(d+1) = sum(abs(dx)==d)/(nt-1);  % relative jump frequency
end

% Plot jump frequencies
d = 0:nc-1;
figure(1)
bar(d,pd)
xlabel('jump distance (cm)')
ylabel('relative frequency')


