Recursive Function and increment global/persistant variable

9 views (last 30 days)
My code goes like below.
function [out1] = MyFun1(Arg1,Arg2,Arg3)
global z
If z~=n (n is a number passed in Arg3 )
function [out2]=MyFun2(Arg1,Arg2,Arg3)
out1=out2;
z=z+1;
MyFun1(Arg1,Arg2,Arg3)
end
out1=out2;
end
I want to take the output of 1st iteration and perform same operation on 1st result and again take that result and perfrom same operation. Repeat the process for z times.
I tried both recursive and persistant but I am not sure what mistake am I doing. Myfun1 and Myfun2 are replica only if i can handle recusrsive withing a single function I can modify my code.
  4 Comments
Amishi
Amishi on 9 Apr 2020
Edited: Amishi on 9 Apr 2020
I want to call a function n times and each iteration i need the 1st output as input.
For Eg if I have a matrix X and for operations I have some matrix A,B,C and so on
1st Iteration
X1= X+A;
2nd iteration
X2=X1+B;
3rd itertaion
X3=X2+C;
I am passing A,B,C as an cell of matrix and final i want to return X3
I rewrote my code as below
% Main function
%%% code for arg1, arg2,arg3;
global P
global Q
P=4;
Q=1;
out =fun1(arg1,arg2,arg3,P,Q);
Function file
fun [out1]=input1(arg1,arg2,arg3,P,Q)
if (Q~=P)
XX=fun2(arg1,arg2,arg3);
input1(arg1,arg2,XX,P,Q+1);
end
out1=XX;
end
so in this case if Q=4 it exits the loop so my intializing issue has been solved
But when i debug the code out1 rolls backs to Q=4,3,2 and the result in out in the main program is not X3 instead X1
I am not sure on how to rectify it. Please help.

Sign in to comment.

Answers (1)

Rik
Rik on 9 Apr 2020
Edited: Rik on 9 Apr 2020
You could do this with a recursive function, but it is a better idea to use a for-loop:
%generate some random data
sz=[5 30];
ABCD=cell(1,4);
for n=1:numel(ABCD),ABCD{n}=rand(sz);end
%now the calculation:
X=ABCD{1};
for n=2:numel(ABCD)
X=X+ABCD{n};
end
Or even better, you could use the sum function, although this only works if this is exactly what you want to do (the for-loop allows function calls if you need them).
tmp=cat(ndims(ABCD{1})+1,ABCD{:});
X=sum(tmp,ndims(tmp));

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!