How can I set the number of iterations to run in a recursive function in Matlab? I have the following function
function t=m(x1,x2)
if x1<0.5
if x2<0.5
t=(0+m(2*x2, 2*x1))/4;
else
t=(1+m(2*x1, 2*x2-1))/4;
end
else
if x2>=0.5
t=(2+m(2*x1-1, 2*x2-1))/4;
else
t=(3+m(1-2*x2, 2-2*x1))/4;
end
end
end
I want it to perform 10^3
iterations.
I tried with
function t=m(x1,x2,iter)
while iter<=10^3
if x1<0.5
if x2<0.5
t=(0+m(2*x2, 2*x1, iter+1))/4;
else
t=(1+m(2*x1, 2*x2-1, iter+1))/4;
end
else
if x2>=0.5
t=(2+m(2*x1-1, 2*x2-1, iter+1))/4;
else
t=(3+m(1-2*x2, 2-2*x1, iter+1))/4;
end
end
end
end
and in the main
x1=0.3;
x2=0.4;
iter=0;
t=m(x1,x2,iter);
but it gives me several errors. Any help?
Firstly, you shouldn't put that loop inside your function. Repeating is the role of recursion. So change your function to:
function t=m(x1,x2,iter)
t = 0;
if iter > 0
if x1<0.5
if x2<0.5
t=(0+m(2*x2, 2*x1, iter-1))/4;
else
t=(1+m(2*x1, 2*x2-1, iter-1))/4;
end
else
if x2>=0.5
t=(2+m(2*x1-1, 2*x2-1, iter-1))/4;
else
t=(3+m(1-2*x2, 2-2*x1, iter-1))/4;
end
end
end
end
(supposing you want it to return 0 after the last iteration)
Now you can call your function like this:
m(0.3, 0.4, 10^3)
But before that, call:
set(0,'RecursionLimit',10^3+2)
For these inputs, it converges to 0.1808 after only 8 iterations.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.