This is the code to generate your $x_n$ estimates in a matrix x, the $n^{th}$ row corresponds to the value of $x_{n-1}$ for a different value of $r$, specified by the column index of $x$. I just plotted a normal plot so you can see the evolution.
X = 100 % first X terms
R = [0.9,1.5,3,4]; % these are the r values
x = zeros(X,length(R)); % initialise x to all zeros
x(1,:) = 0.1 % this is x0
k=1; % set a counter to 1
for r=R
for n = 1:X
x(n+1,k) = r*x(n)*(1-x(n));% for each r and n update x
end
k=k+1;
end
plot(x)% plot them all
legend('r=0.9','r=1.5','r=3','r=4')
You should be able to see this
For a cobweb plot, you need to generate a subplot for each $r$, i.e.
figure
for k = 1:length(R)
subplot(2,2,k)
for n = 1:(X-1)
plot([x(n,k),x(n,k)],[x(n,k),x(n+1,k)])
hold on
plot([x(n,k),x(n+1,k)],[x(n+1,k),x(n+1,k)])
end
title(['Cobweb for r = ', num2str(R(k))])
end
Now, you should see this:
This shows you that for all gives $r$ values, you're going to $x_n \rightarrow 0$
You transformed the method equation wrongly, there are multiple sign errors. It should be
\begin{align}
u_j^{n+1}
&=u_j^n - \frac{p}2(u_{j+1}^n - u_{j-1}^n) + \frac{p^2}{2}(u_{j+1}^n - 2u_j^n + u_{j-1}^n)
\\
&= u_j^n (1-p^2) -\frac{p-p^2}2 u_{j+1}^n +\frac{p+p^2}2 u_{j-1}^n
\end{align}
Implementing this results in a correct looking dynamic
F = @(x) sin(pi*(x-1)).^2 .* (1<x).*(x<2);
n = 200;
x0 = 0; xn = 6;
x = linspace(x0,xn,n+1);
dx = x(2)-x(1);
t = 0;
dt = 0.1*dx;
p = dt/dx;
v = F(x);
%%% Scheme iterations
k=1
while t<4
v(2:n) = (1-p^2)*v(2:n)-0.5*(p-p^2)*v(3:n+1)+0.5*(p+p^2)*v(1:n-1);
v(1) = v(2);
v(n+1) = v(n);
t = t + dt;
if t>k
subplot(4,1,k);
hold on
plot(x,v,'bo');
plot(x,F(x-t),'k-');
ylim([-0.1,1.1]);
grid on;
title(sprintf("t=%.3f",t))
hold off
k=k+1
end
end
Best Answer
I might do it this way: