Storing multiple matrices created by multiple executions of a function

1 Ansicht (letzte 30 Tage)
I have a recursing function that outputs four matrices when the recursion stops. The problem is that (because it's a recursing function) the function runs multiple times simultaniously so I at the end I get a set of four matrices from each finishing function but I don't know from which function it's originating. So my command window shows:
A1 = .. A2=... A3=.. A4=.. A1=.. A2=.. A3=.. ...etc. Where A1, A2, A3 & A4 are the four matrices named by the function. Is there a way to index or store them so that I can acces each matrix individually (my goal is to put them all into one big matrix)?
Thanks for reading!

Akzeptierte Antwort

Stephen23
Stephen23 am 9 Aug. 2019
Bearbeitet: Stephen23 am 9 Aug. 2019
Method one: input/output arguments:
function [A,B] = mainfun(N)
[A,B] = recfun(N,{},{});
end
function [A,B] = recfun(N,A,B) % local function
if N>0
A{end+1} = 1:+1:N; % output data
B{end+1} = N:-1:1; % output data
[A,B] = recfun(N-1,A,B); % recursion
end
end
And tested:
>> [X,Y] = mainfun(4);
>> X{:}
ans =
1 2 3 4
ans =
1 2 3
ans =
1 2
ans =
1
>> Y{:}
ans =
4 3 2 1
ans =
3 2 1
ans =
2 1
ans =
1
Method two: nested function:
function [A,B] = mainfun(N)
A = {};
B = {};
recfun(N);
function recfun(N) % nested function
if N>0
A{end+1} = 1:+1:N; % output data
B{end+1} = N:-1:1; % output data
recfun(N-1); % recursion
end
end
end
And tested:
>> [X,Y] = mainfun(4);
>> X{:}
ans =
1 2 3 4
ans =
1 2 3
ans =
1 2
ans =
1
>> Y{:}
ans =
4 3 2 1
ans =
3 2 1
ans =
2 1
ans =
1

Weitere Antworten (0)

Kategorien

Mehr zu Matrix Indexing finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by