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

6 Ansichten (letzte 30 Tage)
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,:);

Akzeptierte Antwort

Stephen23
Stephen23 am 8 Mär. 2022
Bearbeitet: Stephen23 am 8 Mär. 2022
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 Kommentar
Struggling in MATLAB
Struggling in MATLAB am 8 Mär. 2022
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!

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Programming finden Sie in Help Center und File Exchange

Produkte


Version

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by