Piecewise Iterated Function not looping all the way

2 views (last 30 days)
I am trying to write a program that calculates the value of y after inputting a number into f(x) and as well as f^2(x) and f^3(x) and so on up until f^100(x) but my loop is freezing after 4-5 loops, what could be the error?
x0 = 0.2;
syms x
y = piecewise(0<=x<=0.5, 2*x, 0.5<x<=1, 2*x-1);
for c=0:3
subs(y,x,0.2)
y = piecewise(0<=y<=0.5, 2*y, 0.5<y<=1, 2*y-1);
end

Answers (1)

Shivam Malviya
Shivam Malviya on 14 Jun 2021
Hi Brian!
The execution time of below code increases exponentially with number of iterations, which might be the cause of your issue.
y = piecewise(0<=y<=0.5, 2*y, 0.5<y<=1, 2*y-1);
To check the execution time of your program, you can use the below code: -
x0 = 0.2;
syms x;
y = piecewise(0<=x<=0.5, 2*x, 0.5<x<=1, 2*x-1);
for c=0:10
disp("The iteration number: " + int2str(c))
tic;
subs(y,x,0.2);
subs_exec_time = toc
tic;
y = piecewise(0<=y<=0.5, 2*y, 0.5<y<=1, 2*y-1);
pw_exec_time = toc
end
One possible workaround for this could be that you use the value of the last piecewise function instead of using the previous piecewise function to make the next piecewise function (code given below). This will improve the computational complexity from exponential to constant.
x0 = 0.2;
syms x;
y = piecewise(0<=x<=0.5, 2*x, 0.5<x<=1, 2*x-1);
d = x0;
for c=0:10
disp("The iteration number: " + int2str(c))
d = subs(y, x, d);
end

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!