Storing multiple matrices created by multiple executions of a function

1 回表示 (過去 30 日間)
Ivan Verstraeten
Ivan Verstraeten 2019 年 8 月 9 日
編集済み: Stephen23 2019 年 8 月 9 日
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 Center および File ExchangeMatrix Indexing についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by