Storing multiple matrices created by multiple executions of a function

조회 수: 1 (최근 30일)
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!

채택된 답변

Stephen23
Stephen23 2019년 8월 9일
편집: Stephen23 2019년 8월 9일
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개)

카테고리

Help CenterFile Exchange에서 Operating on Diagonal Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by