![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/282615/image.png)
Recursive Function and increment global/persistant variable
5 次查看(过去 30 天)
显示 更早的评论
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 个评论
回答(1 个)
Rik
2020-4-9
编辑:Rik
2020-4-9
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));
0 个评论
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!