
Recursive Function and increment global/persistant variable
7 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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 commentaires
Réponses (1)
Rik
le 9 Avr 2020
Modifié(e) : Rik
le 9 Avr 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));
0 commentaires
Voir également
Catégories
En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange
Produits
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!