フィルターのクリア

How to use the output of a nested function in parent function?

6 ビュー (過去 30 日間)
Atanu
Atanu 2022 年 3 月 8 日
コメント済み: Atanu 2022 年 3 月 8 日
I trying to make a long function readable. I was planning to write nested function inside the parent function. How can I use the output of a nested function in parent function workspace? I am getting "variable must be explicitly defined before first use" error.
%parent function
function [time_in_feeder_zone, out] = rodent_trial2(rodent, trial_no)
fn_all_data;
%nested function
function [X, Y, all_data] = fn_all_data(~)
% code
end
% 4 quadtrants based on signs
Q1 = all_data(all_data.X>=0 & all_data.Y>=0,:);

採用された回答

Stephen23
Stephen23 2022 年 3 月 8 日
編集済み: Stephen23 2022 年 3 月 8 日
If you define a function with output arguments and you then want to get those outputs then of course you will also need to call the function with those output arguments. This is true for every kind of function, including nested functions.
function [..] = rodent_trial2(rodent, trial_no)
[~,~,out] = fn_all_data(); % you need to call the function with the output arguments!!!
idx = out.X>=0 & out.Y>=0;
Q1 = out(idx,:);
..
%nested function
function [X, Y, all_data] = fn_all_data() % if you defined output arguments here.
% code
all_data = .. whatever
end
end
But I suspect that you were actually attempting to share the data via the parent workspace, perhaps something like this.
function [..] = rodent_trial2(rodent, trial_no)
all_data = []; % must be defined in the parent workspace before calling nested function!
fn_all_data() % no output arguments!
idx = all_data.X>=0 & all_data.Y>=0;
Q1 = all_data(idx,:);
..
%nested function
function fn_all_data() % no output arguments!
% code
all_data = .. whatever
end
end
  1 件のコメント
Atanu
Atanu 2022 年 3 月 8 日
I think I need all X, Y, and all_data in my parent function workspace. SInce I am looping through multiple files to get all X, Y data inside the nested function.
X = cat(1, X, xx); % store XCenter of all files
Y = cat(1, Y, yy);
RT = cat(1, RT, rt);
all_data = table(X, Y, RT);
So, it seems I needed the first part of your answer for now. If I understand correctly I could use the second part if I had X and Y in the parent function workspace.
Thank you very much for the detailed explanation!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeProgramming についてさらに検索

製品


リリース

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by