0

Here I am trying to do the Cobweb diagram for Tent function through MATLAB, and here is the code:


function cobweb(f,a,b,x0,N)

x0 = 0.8; % initial point N = 200; % number of iterations x = linspace(0,1,1000); % space of x

% define the Tent function for i=1:numel(x) if x(i) = 1/2 f(i) = 1.5*(1-x(i)); end end

hold on plot(x,f,'k') hold on plot(x,x,'r')

xlabel('x(t)') ylabel('f(t+1)')

grid on

x(1) = x0;

line([x(1),x(1)],[0,f(x(1))]); line([x(1),f(x(1))],[f(x(1)),f(x(1))]);

for i=1:N x(i+1) = f(x(i)); plot([x(i+1),x(i+1)],[x(i+1),f(x(i+1))]); hold on plot([x(i+1),f(x(i+1))],[f(x(i+1)),f(x(i+1))]); end hold off  

My question is, when I am running the code, MATLAB says:


Array indices must be positive integers or logical values.

Error in cobwebplot (line 31) line([x(1),x(1)],[0,f(x(1))]);  

But I don't understand why here it says so, because I didn't find any non-integer indices here, and can someone help me explain why here it has such error? Thanks!

ZYX
  • 1
  • It looks like $f(x_0)$ evaluates to zero. Is that what you expect? – A rural reader Feb 25 '24 at 22:44
  • A very strange if x(i) = 1/2 which should at least be if x(i) == 1/2 but even under this form , I don't understand how you obtain a tent. I advise you to use a closed form expression for the tent function such as $f(x)=1-abs(abs(x)-abs(x-1))$. – Jean Marie Feb 25 '24 at 23:15
  • I know what you mean here, but the problem is $<$ cannot be shown in the code space. If you click on "Edit" then you can see what I originally wrote in it. It should be: for i=1:numel(x) if x(i) <= 1/2 f(i) = 1.5x(i); elseif x(i) >= 1/2 f(i) = 1.5(1-x(i)); end end – ZYX Feb 25 '24 at 23:24
  • Yes, I have used expression with abs to avoid piecewise expression. But the next problem for my assignment is to do the same process for f(x) = x (0<=x<=1/4), (1-x)/3 (1/4<=x<=1), and in this case I cannot write it in a form with abs, and this is why I post a question here asking how to deal with this case. – ZYX Feb 25 '24 at 23:27
  • 1
    Yes you can ! The function you mention above can be given the closed form : $f(x)=(1/2)abs(x)-(1/6)abs(4x-1)+(1/6)abs(x-1)$. – Jean Marie Feb 26 '24 at 00:10
  • 1
    For cobweb diagrams, you cannot work, as you do, with a discretization of your function. – Jean Marie Feb 26 '24 at 00:13
  • @JeanMarie Thanks so much for your help! I am now able to continue. – ZYX Feb 26 '24 at 00:22

0 Answers0