Storing multiple matrices created by multiple executions of a function
1 view (last 30 days)
Show older comments
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!
0 Comments
Accepted Answer
Stephen23
on 9 Aug 2019
Edited: Stephen23
on 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
0 Comments
More Answers (0)
See Also
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!