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

조회 수: 6 (최근 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
Struggling in MATLAB
Struggling in MATLAB 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