Recursive Function and increment global/persistant variable
9 ビュー (過去 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 件のコメント
参考
カテゴリ
Help Center および File Exchange で Loops and Conditional Statements についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!