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

7 次查看(过去 30 天)
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 CenterFile Exchange 中查找有关 Programming 的更多信息

产品


版本

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by