
How to introduce anonymous function in this code?
9 次查看(过去 30 天)
显示 更早的评论
Hi! So here is a code which I made in class to make a bifurcation diagram but it takes a lot of time to execute. As I've seen how anonymous function speed up the computation considerably, I was wondering if there is a way to implement the said handler in this code:
f=inline('x*(1+r*(1-x))');
for r=0.5:0.01:3
x=0.4;
for i=1:100
x=f(r,x);
end
for i=1:100
x=f(r,x);
plot(r,x,'*')
hold on
end
end
My goal is to achieve the same graph as attached.
0 个评论
回答(1 个)
John D'Errico
2016-9-4
编辑:John D'Errico
2016-9-4
f = @(r,x) x.*(1+r.*(1-x));
To be honest, I'm not sure what your goal is here. It looks like you are trying to solve an equation using a fixed point iteration, but not done terribly efficiently.
A quick check on what SHOULD be happening. You are effectively trying to solve the equation
x*(1+r*(1-x)) - x = 0
Which reduces to
-r*x^2 + r*x = 0
So the value of r is irrelevant to the solution, as long as r is not zero. This problem has two unique roots, at x=0 and x=1.
Solve will tell us that.
syms x r
x = solve(x.*(1+r.*(1-x)) == x)
x =
0
1
So this problem has two solutions, regardless of r. But what happens when we apply fixed point iteration to it, as has been done here?
I'll let the iterative loop go a LONG way out, as this will be quite fast now.
f = @(r,x) x.*(1+r.*(1-x));
r = 0.5:0.01:3;
x = 0.4;
for i=1:10000
x = f(r,x);
end
plot(r,x)
grid on

So it converges to a nice, stable result for r less than 2. Above that point, things go crazy. This is a common behavior of fixed point iteration methods. You need to watch the derivatives of f. But that is a complete lecture on fixed point iteration.
另请参阅
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!