Recursive Function and increment global/persistant variable
8 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
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 comentarios
Respuestas (1)
Rik
el 9 de Abr. de 2020
Editada: Rik
el 9 de Abr. de 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 comentarios
Ver también
Categorías
Más información sobre Loops and Conditional Statements en Help Center y File Exchange.
Productos
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!